<template>
	<view class="page-top-bg"></view>
	<AdaptiveNavBar :showBack="true" :title="pageTitle" :showHome="false" :showShadow="false" text-color="#ffffff"
		background-color="#FC642F" />
	<view class="content-area" :style="{ marginTop: $navbarUtil.getNavbarTotalHeightRpx() }">
		<view class="period-create-container">
			<!-- 加载状态11/12 -->
			<view v-if="loading" class="loading-container">
				<u-loading-icon mode="spinner" size="40" color="#3FBDA3"></u-loading-icon>
				<text class="loading-text">正在加载...</text>
			</view>

			<view v-else class="main-content">
				<!-- 产品信息卡片 -->
				<view class="main-top-period" :style="{ marginTop: $navbarUtil.getNavbarTotalHeightRpx() }">
					<view v-if="productInfo && productInfo.mainInfo" class="product-card-wrapper">
						<ProductCard :info="productInfo" />
					</view>

					<!-- 班期选择区块 -->
					<section class="section" style="position: relative;margin: 0rpx;">
						<view class="section-header" style="padding: 20rpx 0rpx;">
							<view class="section-header__left">
								<view class="section-header__icon-wrapper">
									<FontIcon name="icon-xuanzebanqi"
										class="section-header__icon section-header__font_icon"></FontIcon>
								</view>

								<view class="section-header__title">班期选择</view>
							</view>
						</view>

						<!-- 班期卡片列表（默认横向滑动，不换行；点击"全部班期"展开为多行） -->
						<view v-if="displayedPeriods" class="period-cards-container"
							:class="{ expanded: showAllPeriods }">
							<view v-for="periodItem in displayedPeriods" :key="periodItem.periodId" class="period-card"
								:class="{
									'selected': periodItem.isSelected,
									'disabled': !periodItem.isSelected && !isPeriodSelectable(periodItem),
									'a-class-selected': isAClassDateSelection && periodItem.isSelected
								}">
								<!-- 暂时不显示。后续在其他地方调用才会显示出来 -->
								<view class="period-badge" v-if="false">{{ maxPeople }}</view>
								<view class="period-card__date">
									<text class="period-card__month-day">{{ formatMonthDay(periodItem.DateName)
									}}</text>
								</view>
								<view class="period-card__week">{{ periodItem.WeekName }}</view>
							</view>
							<!-- 占位标签（防止被按钮遮挡） -->
							<view class="all-periods-button-spacer"></view>
							<!-- 全部班期按钮 -->
							<view class="all-periods-button" @tap.stop="chooseDate" v-if="!isReadonly">
								<text>全部</text>
								<text>班期</text>
							</view>
							<view v-if="displayedPeriods.length === 0" class="empty-dates">

								<text class="empty-text">请先选择班期</text>
							</view>
						</view>

						<!-- 渠道价格显示（仅申请调用模式显示） -->
						<!-- <view v-if="isApplyCall && selectedDates && selectedDates.some(item => item.isSelected)"
							class="channel-price-info">
							<text class="channel-price-label" style="color: #999999;">渠道价：</text>
							<view class="channel-price-value">
								<text class="currency">¥</text>
								<text class="price-int">{{ selectedPriceParts.intPart }}</text>
								<text class="price-dec">.{{ selectedPriceParts.decPart }}</text>
								<text class="per">元/人</text>
							</view>
						</view> -->
					</section>
				</view>

				<section class="section">
					<!-- 销售区域输入 -->
					<view style="display: flex;align-items: center;">
						<view class="section-header" style="flex:1">
							<view class="section-header__icon-wrapper">
								<FontIcon name="icon-xuanzebanqi"
									class="section-header__icon section-header__font_icon"></FontIcon>
							</view>
							<text class="section-header__title">已选班期</text>
						</view>
						<view style="margin-right: 28rpx;font-size: 28rpx;color: #333333;">{{ selectablePeriodsCount }}期
						</view>
					</view>
				</section>

				<!-- 市场渠道设置 -->
				<section class="section">
					<view class="section-header">
						<view class="section-header__icon-wrapper">
							<FontIcon name="icon-shichangqudaoshezhi" :size="18"
								class="section-header__icon section-header__font_icon"></FontIcon>
						</view>
						<text class="section-header__title">市场渠道设置</text>
					</view>
					<view class="form-group" style="display: flex;justify-content: space-between;">
						<view class="form-group__label">销售模式</view>
						<picker @change="handlePickerChange" :value="salesModeIndex" :range="salesModeOptions"
							data-type="salesMode">
							<view class="form-group__picker" style="color: #333333;font-size: 24rpx;line-height: 60rpx;">
								{{ salesModeOptions[salesModeIndex] }}
								<img src="../../static/systemIcon/arrow-bottom.png"
									style="width: 32rpx; height: 32rpx; margin-left: 8rpx;margin-top: 14rpx;" mode="aspectFit" />
							</view>
						</picker>
					</view>
				</section>

				<!-- 销售区域输入 -->
				<!-- <section class="section">
					<view style="display: flex;align-items: center;">
						<view class="section-header" style="flex:1">
							<view class="section-header__icon-wrapper">
								<FontIcon name="icon-xuanzebanqi"
									class="section-header__icon section-header__font_icon"></FontIcon>
							</view>
							<text class="section-header__title">已选班期</text>
						</view>
						<view style="margin-right: 28rpx;font-size: 28rpx;color: #333333;">{{ selectedDates.length }}期
						</view>
					</view>
				</section> -->

				<!-- 泛营期设置 -->
				<section class="section" v-if="businessType !== 3">
					<view class="section-header">
						<view class="section-header__icon-wrapper">
							<FontIcon name="icon-shichangqudaoshezhi" :size="24"
								class="section-header__icon section-header__font_icon"></FontIcon>
						</view>
						<text class="section-header__title">泛营期设置</text>
					</view>
					<!-- 一二类商家，不是组团业务的，也就是不是从产品详情当中的申请调用进入到该页面 -->
					<template v-if="(businessType === 1 || businessType === 2) && productType !== '4' && !isApplyCall">
						<view class="number-input-group">
							<view class="number-input-group__label" style="color: #000000;">渠道申请截止：行程日前</view>
							<view class="number-input-group__control">
								<view class="number-input-group__buttons">
									<view class="number-input-decrement"
										:class="{ 'disabled': applicationDeadline <= CONSTANTS.MIN_APPLICATION_DEADLINE }"
										@tap="adjustNumber('applicationDeadline', -1)">-</view>
									<input type="number" class="number-input-group__input" v-model="applicationDeadline"
										@blur="validateNumber('applicationDeadline')" />
									<view class="number-input-increment"
										:class="{ 'disabled': applicationDeadline >= applicationDeadlineLimit }"
										@tap="adjustNumber('applicationDeadline', 1)">+</view>
								</view>
								<text class="number-input-group__unit">天</text>
							</view>
						</view>
						<view class="section-description">申请特定班期必须提前的天数，设定到期后，该班期不再接受新的合作申请</view>

						<view class="number-input-group margin-top-large">
							<view class="number-input-group__label" style="color: #000000;">成团确认日期：行程日前<text>
									{{ applicationDeadline }}~</text></view>
							<view class="number-input-group__control">
								<view class="number-input-group__buttons">
									<view class="number-input-decrement" :class="{ 'disabled': confirmationTime <= 3 }"
										@tap="adjustNumber('confirmationTime', -1)">-</view>
									<input type="number" class="number-input-group__input" v-model="confirmationTime"
										@blur="validateNumber('confirmationTime')" />
									<view class="number-input-increment"
										:class="{ 'disabled': confirmationTime >= (applicationDeadline - 3) }"
										@tap="adjustNumber('confirmationTime', 1)">+</view>
								</view>
								<text class="number-input-group__unit">天</text>
							</view>
						</view>
						<view class="section-description">设定时间到期后，成团人数达标，解除对接团方的人数责任</view>
					</template>
					<!-- 组团业务，也就是从产品的申请调用按钮进入到该页面 -->
					<template v-if="isApplyCall && (businessType === 2 || productType === '4')">
						<view class="number-input-group">
							<view class="number-input-group__label" style="color: #000000;">校组申请截止：行程日前</view>
							<view class="number-input-group__control">
								<view class="number-input-group__buttons">
									<view class="number-input-decrement"
										:class="{ 'disabled': applicationDeadline <= CONSTANTS.MIN_APPLICATION_DEADLINE }"
										@tap="adjustNumber('applicationDeadline', -1)">-</view>
									<input type="number" class="number-input-group__input" v-model="applicationDeadline"
										@blur="validateNumber('applicationDeadline')" />
									<view class="number-input-increment"
										:class="{ 'disabled': applicationDeadline >= applicationDeadlineLimit }"
										@tap="adjustNumber('applicationDeadline', 1)">+</view>
								</view>
								<text class="number-input-group__unit">天</text>
							</view>
						</view>
						<view class="section-description">申请特定班期必须提前的天数，设定到期后，该班期不再接受新的合作申请</view>

						<view class="number-input-group margin-top-large">
							<view class="number-input-group__label" style="color: #000000;">成团确认日期：行程日前</view>
							<view class="number-input-group__control">
								<view class="number-input-group__buttons">
									<view class="number-input-decrement" :class="{ 'disabled': confirmationTime <= 3 }"
										@tap="adjustNumber('confirmationTime', -1)">-</view>
									<input type="number" class="number-input-group__input" v-model="confirmationTime"
										@blur="validateNumber('confirmationTime')" />
									<view class="number-input-increment"
										:class="{ 'disabled': confirmationTime >= (applicationDeadline - 3) }"
										@tap="adjustNumber('confirmationTime', 1)">+</view>
								</view>
								<text class="number-input-group__unit">天</text>
							</view>
						</view>
						<view class="section-description">设定时间到期后，成团人数达标，解除对接团方的人数责任</view>
					</template>

					<!-- 三类商家（businessType=3）或非申请调用模式：显示渠道申请截止 -->
					<template v-if="!isApplyCall && businessType === 3">
						<view class="number-input-group">
							<view class="number-input-group__label" style="color: #000000;">渠道申请截止：行程日前</view>
							<view class="number-input-group__control">
								<view class="number-input-group__buttons">
									<!-- 减号按钮 -->
									<view class="number-input-decrement"
										:class="{ 'disabled': applicationDeadline <= CONSTANTS.MIN_APPLICATION_DEADLINE }"
										@tap="adjustNumber('applicationDeadline', -1)">-</view>
									<!-- 数值输入框 -->
									<input type="text" class="number-input-value" v-model="applicationDeadline"
										@blur="validateNumber('applicationDeadline')" />
									<!-- 加号按钮 -->
									<view class="number-input-increment"
										:class="{ 'disabled': applicationDeadline >= applicationDeadlineLimit }"
										@tap="adjustNumber('applicationDeadline', 1)">+</view>
								</view>
								<text class="number-input-group__unit">天</text>
							</view>
						</view>
						<view class="section-description">申请特定班期必须提前的天数，设定到期后，该班期不再接受新的合作申请</view>
					</template>
					<!-- 三类商家申请调用模式：回显成团确认时间（只读） -->
					<template v-if="isApplyCall && businessType === 3">
						<view class="number-input-group">
							<view class="number-input-group__label" style="color: #000000;">成团确认日期：行程日前</view>
							<view class="number-input-group__control">
								<view class="number-input-group__display">
									<text class="number-input-group__value">{{ confirmationTime }}</text>
									<text class="number-input-group__unit">天</text>
								</view>
							</view>
						</view>
						<view class="section-description">由上游商家设定，设定时间到期后，成团人数达标，解除对接团方的人数责任</view>
					</template>
				</section>

				<!-- 名额设置 -->
				<section class="section" v-if="businessType !== 3">
					<view class="section-header">
						<view class="section-header__icon-wrapper">
							<FontIcon name="icon-mingeshezhi" class="section-header__icon section-header__font_icon">
							</FontIcon>
						</view>
						<text class="section-header__title" v-if="isApplyCall && businessType === 2">名额设置/申请名额</text>
						<text class="section-header__title" v-else>名额设置</text>
					</view>

					<!-- 二类商家（businessType=2）申请调用模式 -->
					<template v-if="businessType !== 3">
						<view class="number-input-group margin-top-large">
							<view class="number-input-group__label">每团满员人数</view>
							<view class="number-input-group__control">
								<view class="number-input-group__buttons">
									<view class="number-input-decrement"
										:class="{ 'disabled': maxPeople <= 10 || maxPeople <= minPeople }"
										@tap="adjustNumber('maxPeople', -1)">-</view>
									<input type="number" class="number-input-group__input" v-model="maxPeople"
										@blur="validateNumber('maxPeople')" />
									<view class="number-input-increment"
										:class="{ 'disabled': maxPeople >= maxPeopleLimit }"
										@tap="adjustNumber('maxPeople', 1)">+</view>
								</view>
								<text class="number-input-group__unit">人</text>
							</view>
						</view>
						<view class="section-description">报名达到该人数后（10-50）</view>
						<view class="number-input-group margin-top-large">
							<view class="number-input-group__label">最低成团人数</view>
							<view class="number-input-group__control">
								<view class="number-input-group__buttons">
									<view class="number-input-decrement"
										:class="{ 'disabled': minPeople <= minPeopleLimit }"
										@tap="adjustNumber('minPeople', -1)">-</view>
									<input type="number" class="number-input-group__input" v-model="minPeople"
										@blur="validateNumber('minPeople')" />
									<view class="number-input-increment"
										:class="{ 'disabled': minPeople >= 30 || minPeople >= maxPeople }"
										@tap="adjustNumber('minPeople', 1)">+</view>
								</view>
								<text class="number-input-group__unit">人</text>
							</view>
						</view>
						<view class="section-description">未达到成团人数或组团等待的期限到期后，将全额退款（10-30）</view>

						<view class="number-input-group margin-top-large">
							<view class="number-input-group__label">每期服务承载最大团数</view>
							<view class="number-input-group__control">
								<view class="number-input-group__buttons">
									<view class="number-input-decrement" :class="{ 'disabled': groupCount <= 1 }"
										@tap="adjustNumber('groupCount', -1)">-</view>
									<input type="number" class="number-input-group__input" v-model.number="groupCount"
										@blur="validateNumber('groupCount')" />
									<view class="number-input-increment"
										:class="{ 'disabled': groupCount >= groupCountLimit }"
										@tap="adjustNumber('groupCount', 1)">+</view>
								</view>
								<text class="number-input-group__unit">团</text>
							</view>
						</view>
						<view class="section-description">根据本期承载的最大人数综合配置（1-20）</view>
					</template>

					<!-- 非申请调用模式：显示默认名额设置 -->
					<template v-if="false">
						<view class="number-input-group">
							<view class="number-input-group__label">单期接团承载人数上限</view>
							<view class="number-input-group__control">
								<view class="number-input-group__buttons">
									<view class="number-input-decrement" :class="{ 'disabled': maxPeople <= 10 }"
										@tap="adjustNumber('maxPeople', -1)">-</view>
									<input type="number" class="number-input-group__input" v-model="maxPeople"
										@blur="validateNumber('maxPeople')" />
									<view class="number-input-increment" :class="{ 'disabled': maxPeople >= 50 }"
										@tap="adjustNumber('maxPeople', 1)">+</view>
								</view>
								<text class="number-input-group__unit">人</text>
							</view>
						</view>
						<view class="section-description">报名达到该人数后，系统将限制后续报名（10-50）</view>

						<view class="number-input-group margin-top-large">
							<view class="number-input-group__label">单期单团名额下限</view>
							<view class="number-input-group__control">
								<view class="number-input-group__buttons">
									<view class="number-input-decrement" :class="{ 'disabled': minPeople <= 10 }"
										@tap="adjustNumber('minPeople', -1)">-</view>
									<input type="number" class="number-input-group__input" v-model="minPeople"
										@blur="validateNumber('minPeople')" />
									<view class="number-input-increment" :class="{ 'disabled': minPeople >= 30 }"
										@tap="adjustNumber('minPeople', 1)">+</view>
								</view>
								<text class="number-input-group__unit">人</text>
							</view>
						</view>
						<view class="section-description">成团最少人数要求（10-30）</view>
					</template>
				</section>


				<!-- 小组名额设置（二类商家专用 - 随队比例） -->
				<section v-if="(isApplyCall && businessType === 2) || (businessType === 2 && productType === '2')"
					class="section">
					<view class="section-header">
						<text class="section-header__icon cuIcon-group"></text>
						<text class="section-header__title">小组名额设置（随队比例）</text>
					</view>
					<view class="number-input-group">
						<view class="number-input-group__label">每小组名额上限</view>
						<view class="number-input-group__control">
							<view class="number-input-group__buttons">
								<view class="number-input-decrement" :class="{ 'disabled': groupMaxPeople <= 6 }"
									@tap="adjustNumber('groupMaxPeople', -1)">-</view>
								<input type="number" class="number-input-group__input" v-model="groupMaxPeople"
									@blur="validateNumber('groupMaxPeople')" />
								<view class="number-input-increment" :class="{ 'disabled': groupMaxPeople >= 20 }"
									@tap="adjustNumber('groupMaxPeople', 1)">+</view>
							</view>
							<text class="number-input-group__unit">人</text>
						</view>
					</view>
					<view class="section-description">根据本次上架产品与参营合同，按1:20最高比例配小组（6-20）</view>

					<view class="number-input-group margin-top-large">
						<view class="number-input-group__label">每小组名额下限</view>
						<view class="number-input-group__control">
							<view class="number-input-group__buttons">
								<view class="number-input-decrement" :class="{ 'disabled': groupMinPeople <= 5 }"
									@tap="adjustNumber('groupMinPeople', -1)">-</view>
								<input type="number" class="number-input-group__input" v-model="groupMinPeople"
									@blur="validateNumber('groupMinPeople')" />
								<view class="number-input-increment" :class="{ 'disabled': groupMinPeople >= 8 }"
									@tap="adjustNumber('groupMinPeople', 1)">+</view>
							</view>
							<text class="number-input-group__unit">人</text>
						</view>
					</view>
					<view class="section-description">根据本次上架产品与参营合同，按1:6最低比例配小组（5-8）</view>
				</section>


				<section class="section"
					v-if="(productType !== '1' && productType !== '3') || (isApplyCall && businessType === 2)">
					<view class="section-header">
						<view class="section-header__icon-wrapper">
							<FontIcon name="icon-youxue" class="section-header__icon section-header__font_icon">
							</FontIcon>
						</view>
						<text class="section-header__title" style="flex:1">接送/集散地点</text>
						<text style="color:#999999;font-size:24rpx">区/县级</text>
					</view>
					<!-- 接送区域 省市区选择器（非businessType=3时显示） -->
					<view class="gather-area-select" v-if="businessType !== 3">
						<picker mode="region" :value="regionValue" @change="onRegionChange">
							<view class="gather-area-picker-wrapper">
								<view class="gather-area-picker">
									<text class="picker-value">{{ gatherProvince || '请选择省份' }}</text>
									<img src="../../static/systemIcon/arrow-bottom.png"
										style="width: 32rpx; height: 32rpx; margin-left: 8rpx;" mode="aspectFit" />
								</view>
							</view>
						</picker>
						<picker mode="region" :value="regionValue" @change="onRegionChange">
							<view class="gather-area-picker-wrapper">
								<view class="gather-area-picker">
									<text class="picker-value">{{ gatherCity || '请选择城市' }}</text>
									<img src="../../static/systemIcon/arrow-bottom.png"
										style="width: 32rpx; height: 32rpx; margin-left: 8rpx;" mode="aspectFit" />
								</view>
							</view>
						</picker>
						<picker mode="region" :value="regionValue" @change="onRegionChange">
							<view class="gather-area-picker-wrapper">
								<view class="gather-area-picker">
									<text class="picker-value">{{ gatherDistrict || '请选择区/县' }}</text>
									<img src="../../static/systemIcon/arrow-bottom.png"
										style="width: 32rpx; height: 32rpx; margin-left: 8rpx;" mode="aspectFit" />
								</view>
							</view>
						</picker>
					</view>
					<!-- 接驳地点 地图地址选择器（businessType=3时显示） -->
					<view class="gather-address-select" v-else>
						<view class="gather-address-content" @tap="selectGatherAddress">
							<view v-if="gatherAreaDisplay" class="gather-address-display">
								<text v-if="getAddressName(gatherAreaDisplay)" class="gather-address-name">{{
									getAddressName(gatherAreaDisplay) }}</text>
								<text v-if="getAddressLocation(gatherAreaDisplay)" class="gather-address-location">{{
									getAddressLocation(gatherAreaDisplay) }}</text>
							</view>
							<text v-else class="gather-address-placeholder">请点击右侧图标选择定位</text>
						</view>
						<view class="gather-location-icon" @tap="selectGatherAddress">
							<u-icon name="map" color="#FFF" size="26"></u-icon>
						</view>
					</view>
				</section>

				<!-- 组团社联系人信息（三类商家申请调用时显示） -->
				<section class="section" v-if="isApplyCall && businessType === 3 && sourceContactList.length > 0">
					<view class="section-header">
						<view class="section-header__icon-wrapper">
							<FontIcon name="icon-lianxiren" class="section-header__icon section-header__font_icon">
							</FontIcon>
						</view>
						<text class="section-header__title">组团社联系人</text>
					</view>
					<view class="working-box">
						<view class="working-item" v-for="(contact, index) in sourceContactList" :key="index">
							<view class="working-avatar"
								style="width: 88rpx;height: 88rpx;border-radius: 5000rpx;background: #eeeeee;overflow: hidden;display: flex;align-items: center;justify-content: center;">
								<image v-if="contact.avatar" :src="contact.avatar" mode="aspectFill"
									style="width: 100%;height: 100%;">
								</image>
								<u-icon v-else name="account" size="44" color="#999999"></u-icon>
							</view>
							<view class="working-info">
								<view class="woking-info-top">{{ contact.name }}<text>{{ contact.category }}</text>
								</view>
								<view class="woking-info-bottom">{{ contact.phone }}</view>
							</view>
						</view>
					</view>
					<view class="section-description" style="color: #999999; font-size: 24rpx; margin-top: 20rpx;">
						备注：此为上游组团社的联系人信息，由系统自动获取
					</view>
				</section>

				<!-- 工作人员配置 -->
				<section class="section">
					<view class="section-header">
						<view class="section-header__icon-wrapper">
							<FontIcon name="icon-lianxiren" class="section-header__icon section-header__font_icon">
							</FontIcon>
						</view>
						<text class="section-header__title" v-if="isApplyCall && businessType === 2">组团社联系人</text>
						<text class="section-header__title" v-else-if="isApplyCall && businessType === 3">随团工作人员</text>
						<text class="section-header__title" v-else>联系人</text>
					</view>
					<view class="working-box">
						<view class="working-item" v-for="(staff, index) in staffList" :key="index">
							<view class="working-avatar"
								style="width: 88rpx;height: 88rpx;border-radius: 5000rpx;background: #eeeeee;overflow: hidden;display: flex;align-items: center;justify-content: center;">
								<image v-if="staff.avatar" :src="staff.avatar" mode="aspectFill"
									style="width: 100%;height: 100%;">
								</image>
								<u-icon v-else name="account" size="44" color="#999999"></u-icon>
							</view>
							<view class="working-info">
								<view class="woking-info-top">{{ staff.name }}<text>{{ staff.category }}</text></view>
								<view class="woking-info-bottom">{{ staff.phone }}</view>
							</view>
							<view class="working-btn">
								<view class="working-delete" @tap="deleteStaff(index)">删除</view>
							</view>
						</view>
						<view class="working-none" v-if="staffList.length == 0">
							暂无产品详情咨询联系人，请添加
						</view>
					</view>
					<view class="working-bottom">
						<view class="working-bottom-top">
							<!-- <view>备注：随着团队报名人员的增多，</view>
							<view style="margin-top:10rpx">您可能需要添加更多的工作人员</view> -->
						</view>
						<view class="working-bottom-bottom" @tap="showStaffPopup">
							<view style="font-size:24rpx">+ 添加</view>
						</view>
					</view>
				</section>

				<!-- 小组名额设置（ -- 随队比例） -->
				<section v-if="isApplyCall && businessType === 3" class="section">
					<view class="section-header">
						<text class="section-header__icon cuIcon-group"></text>
						<text class="section-header__title">小组名额设置（随队比例）</text>
					</view>
					<view class="group-quota-summary">
						<text class="summary-text">每小组名额上限 {{ groupMaxPeople }} 人，共 {{ groupsCount }} 个小组</text>
						<text class="summary-hint">每添加一名随团服务人员，可新增一组名额</text>
					</view>

					<view class="group-quota-summary">
						<text class="summary-text">每小组名额下限 {{ groupMinPeople }} 人</text>
						<text class="summary-hint">如实际报名低于该人数，可由旅行社研判为退单，或支付随队人员的行程费用</text>
					</view>
				</section>

				<!-- 工作人员配置弹窗 -->
				<u-popup ref="staffPopup" mode="bottom" :show="showStaffPopupForm" @close="closeStaffPopup" :round="20"
					:mask-close-able="true">
					<view class="staff-popup-container">
						<view class="staff-popup-header">
							<text class="staff-popup-title" v-if="isApplyCall && businessType === 2">组团联系人</text>
							<text class="staff-popup-title" v-else-if="isApplyCall && businessType === 3">随团工作人员</text>
							<text class="staff-popup-title" v-else>工作人员配置</text>
							<u-icon name="close" size="28" @click="closeStaffPopup"></u-icon>
						</view>

						<scroll-view class="" scroll-y>
							<!-- 添加联系人表单 -->
							<view class="staff-add-form">
								<view class="staff-add-form__title">添加联系人</view>
								<view class="staff-add-form__fields">
									<view class="staff-add-form__field">
										<text class="staff-add-form__label">类型</text>
										<picker @change="handleContactTypeChange" :value="contactTypeIndex"
											:range="contactTypeOptions" range-key="label">
											<view class="staff-add-form__input"
												:style="{ color: newStaff.category ? '#333333' : '#999999' }">
												{{ newStaff.category || '请选择类型' }}
												<img src="../../static/systemIcon/arrow-bottom.png"
													style="width: 32rpx; height: 32rpx; margin-left: 8rpx;margin-top: 16rpx; float: right;"
													mode="aspectFit" />
											</view>
										</picker>
									</view>
									<view class="staff-add-form__field">
										<text class="staff-add-form__label">姓名</text>
										<input class="staff-add-form__input" v-model="newStaff.name"
											placeholder="请输入姓名" />
									</view>
									<view class="staff-add-form__field">
										<text class="staff-add-form__label">电话</text>
										<input class="staff-add-form__input" v-model="newStaff.phone"
											placeholder="请输入电话" type="number" />
									</view>
								</view>
								<view class="staff-add-form__actions">
									<button class="staff-add-form__cancel" @tap="cancelAddStaff">取消</button>
									<button class="staff-add-form__confirm" @tap="confirmAddStaff">确认</button>
								</view>
							</view>
						</scroll-view>
					</view>
				</u-popup>

				<!-- 服务售价 -->
				<section class="section">
					<view class="section-header">
						<view class="section-header__icon-wrapper">
							<FontIcon name="icon-fuwujiage" class="section-header__icon section-header__font_icon">
							</FontIcon>
						</view>
						<text class="section-header__title">服务售价</text>
					</view>

					<!-- 泛营地接待（productType=1）和目的地接待（productType=3）价格（非申请调用模式或一类商家/B2创建目的地接待） -->
					<view
						v-if="(!isApplyCall && (businessType === 1 || productType === '3')) || (isApplyCall && businessType === 1)"
						class="price-input-group">
						<view class="price-input-group__row">
							<view class="price-input-group__label" style="">服务售价-渠道
								<image src="../../static/icons/question-red.svg"
									style="width: 32rpx; height: 32rpx; margin-left: 8rpx; vertical-align: middle;"
									mode="aspectFit" @tap="showPriceModalByKey('servicePrice1')" />
							</view>
							<view class="price-input-group__input-wrapper">
								<view><text style="color: #999999;">￥</text></view>
								<input type="number" :class="['price-input-group__input', { 'has-value': price }]"
									placeholder-style="color:#999999;font-weight: 400;" v-model="price"
									@input="calculateEstimatedPrice" @blur="validatePrice" placeholder="请输入金额" />
								<text class="price-input-group__currency">CNY/人</text>
							</view>
						</view>
						<view class="price-input-group__divider"></view>
						<view class="price-input-group__row">
							<view class="price-input-group__label">结算金额</view>
							<text class="price-input-group__estimate"><text style="color:#000000">{{
								formattedEstimatedPrice }}</text>
								CNY/人</text>
						</view>
						<view class="price-input-group__description">扣收软件技术服务费（费率{{ rate * 100 }}%）后的实际到账金额</view>
					</view>

					<!-- 二类商家其他产品类型价格（非申请调用模式 - 创建班期，排除目的地接待） -->
					<view v-if="!isApplyCall && businessType === 2 && productType !== '3'" class="price-input-group">
						<view class="price-input-group__row">
							<view class="price-input-group__label" style="color: #000000;">服务售价-渠道
								<image src="../../static/icons/question-red.svg"
									style="width: 32rpx; height: 32rpx; margin-left: 8rpx; vertical-align: middle;"
									mode="aspectFit" @tap="showPriceModalByKey('servicePrice2')" />
							</view>
							<view class="price-input-group__input-wrapper"><text style="color: #999999;">￥</text>
								<input type="number"
									:class="['price-input-group__input', { 'has-value': secondServicePrice }]"
									v-model="secondServicePrice" @input="calculateType2Prices" @blur="validatePrice"
									placeholder="请填写金额" />
								<text class="price-input-group__currency">CNY/人</text>
							</view>
						</view>
						<view class="price-input-group__divider"></view>
						<view class="price-input-group__row">
							<view class="price-input-group__label">结算金额
							</view>
							<text class="price-input-group__estimate"><text style="color:#000000">{{
								formattedEstimatedPrice }}</text>
								CNY/人</text>
						</view>
						<view class="price-input-group__description">扣收软件技术服务费（费率{{ rate * 100 }}%）后的实际到账金额</view>
						<!-- <view class="price-input-group__divider"></view>
					<view class="price-input-group__row" style="margin-top: 30rpx;">
						<view class="price-input-group__label" style="font-weight: 700;">合计售价</view>
						<text class="price-input-group__estimate"><text style="color:#E64D42">¥{{
								secondTotalPrice || '0.00' }}</text> CNY/人</text>
					</view>
					<view class="price-input-group__description">研学服务售价（已包含组团增值服务）</view> -->
					</view>

					<!-- 二类商家价格（申请调用模式） -->
					<view v-if="isApplyCall && businessType === 2" class="price-input-group">
						<view class="price-input-group__row">
							<view class="price-input-group__label">目的地接待服务售价</view>
							<text class="price-input-group__estimate"><text style="color:#000000">¥{{
								destinationServicePrice || '0.00'
							}}</text>
								CNY/人</text>
						</view>
						<view class="price-input-group__description">备注*指目的地接待服务商给出的报价</view>
						<view class="price-input-group__divider"></view>
						<view class="price-input-group__row" style="margin-top: 30rpx;">
							<view class="price-input-group__label" style="font-weight: 700;">组团增值服务售价
								<image src="../../static/icons/question-red.svg"
									style="width: 32rpx; height: 32rpx; margin-left: 8rpx; vertical-align: middle;"
									mode="aspectFit" @tap="showPriceModalByKey('servicePrice2')" />
							</view>
							<view class="price-input-group__input-wrapper"><text style="color: #999999;">￥</text>
								<input type="number"
									:class="['price-input-group__input', { 'has-value': groupAddedServicePrice }]"
									v-model="groupAddedServicePrice" @input="calculateType2Prices"
									placeholder="请输入金额" />
								<text class="price-input-group__currency">CNY/人</text>
							</view>
						</view>
						<view class="price-input-group__divider"></view>
						<view class="price-input-group__row">
							<view class="price-input-group__label">预估增值结算金额
								<text class="price-input-group__question cuIcon-question text-red"
									@tap="showPriceModal"></text>
							</view>
							<text class="price-input-group__estimate"><text style="color:#000000">¥{{
								formattedEstimatedGroupSettlement
							}}</text> CNY/人</text>
						</view>
						<view class="price-input-group__description">扣收平台软件技术服务费（费率{{ rate * 100 }}%）后的实际到账金额</view>
						<view class="price-input-group__divider"></view>
						<view class="price-input-group__row" style="margin-top: 30rpx;">
							<view class="price-input-group__label">合单售价(面向渠道)</view>
							<text class="price-input-group__estimate" style="font-size: 28rpx;"><text
									style="color:#E64D42">¥{{
										formattedTotalPrice }}</text> CNY/人</text>
						</view>
						<view class="price-input-group__description">指终端消费者预订、购买该服务的价格</view>
					</view>

					<!-- 三类商家价格（申请调用模式） -->
					<view v-if="isApplyCall && businessType === 3" class="price-input-group">
						<view class="price-input-group__row">
							<view class="price-input-group__label">上游及组团服务API渠道售价</view>
							<text class="price-input-group__estimate">¥{{ formattedUpstreamApiPrice }}
								CNY/人</text>
						</view>
						<view class="price-input-group__description">需将上级及组团服务提供的价格传给您留收该人对人起的费用</view>
						<view class="price-input-group__divider"></view>
						<view class="price-input-group__row" style="margin-top: 30rpx;">
							<view class="price-input-group__label">随队增值服务价格</view>
							<view class="price-input-group__input-wrapper"><text style="color: #999999;">￥</text>
								<input type="number"
									:class="['price-input-group__input', { 'has-value': escortAServicePrice }]"
									v-model="escortAServicePrice" @input="calculateType3Prices" placeholder="请填写金额" />
								<text class="price-input-group__currency">CNY/人</text>
							</view>
						</view>
						<view class="price-input-group__description">需将增供您随队服务的对人起费用</view>
						<view class="price-input-group__divider"></view>
						<view class="price-input-group__row">
							<view class="price-input-group__label">随队服务结算金额</view>
							<text class="price-input-group__estimate">¥{{ formattedEscortASettlement }} CNY/人</text>
						</view>
						<view class="price-input-group__description">扣收平台软件技术服务费（费率{{ rate * 100 }}%）后的实际到账金额</view>
						<view class="price-input-group__divider"></view>
						<view class="price-input-group__row" style="margin-top: 30rpx;">
							<view class="price-input-group__label">合单售价
							</view>
							<text class="price-input-group__estimate" style="font-size: 28rpx;"><text
									style="color:#E64D42">¥{{
										formattedTotalPrice }}</text> CNY/人</text>
						</view>
						<view class="price-input-group__description">需将下得给分销渠道的最终费价</view>
					</view>
				</section>

				<!-- 协议确认 -->
				<view class="agreement-section">
					<checkbox @tap="toggleAgreement" :checked="agreementChecked" color="#3FBDA3" value="A"></checkbox>
					<view>
						<text class="agreement-section__text">我已阅读并同意</text>
						<template v-for="(agreement, index) in getAgreements" :key="index">
							<text class="agreement-section__link" @tap="showAgreement(agreement)">《{{ agreement
							}}》</text>
							<text v-if="index < getAgreements.length - 1" class="agreement-section__text">、</text>
						</template>
					</view>
				</view>
			</view>

			<!-- 底部按钮 -->
			<view class="bottom-actions">
				<view class="bottom-actions__back" @tap="previewProduct">预览</view>
				<view class="bottom-actions__middle" @tap="saveDraft">存草稿</view>
				<view class="bottom-actions__submit" @tap="submitPeriod" :class="{ 'disabled': !canSubmit }">上架售卖</view>
			</view>
		</view>
	</view>

</template>

<script>
import ProductCard from '@/components/ProductCard.vue'
import DateCard from '@/components/DateCard.vue'
import FontIcon from '@/components/FontIcon.vue'
import {
	request
} from '@/utils/request'
import {
	mergeAllProducts
} from '@/utils/productUtil'

// 常量定义
const CONSTANTS = {
	SERVICE_FEE_RATE: 0.06,
	MIN_APPLICATION_DEADLINE: 7,
	MAX_APPLICATION_DEADLINE: 60,
	MIN_PEOPLE: 10,
	MAX_PEOPLE: 50,
	MIN_GROUP_PEOPLE: 10,
	MAX_GROUP_PEOPLE: 30,
	DEFAULT_GROUP_COUNT: 10
}


export default {
	name: 'periodCreate',
	components: {
		ProductCard,
		DateCard,
		FontIcon
	},
	data() {
		return {
			// 常量
			CONSTANTS: CONSTANTS,

			// 加载状态
			loading: false,

			// 产品信息
			productInfo: {},
			productId: 0,
			oldProductId: 0,
			PeriodId: 0,

			// 班期相关
			selectedDates: [],
			periodList: [],
			availablePeriods: [], // 从后端获取的班期数据
			selectedPeriodIds: [], // 选中的班期ID列表
			sourcePeriodId: '', // 从产品详情页传递过来的真实班期ID
			skuId: '', // 从产品详情页传递过来的SKU ID

			// 班期编辑模式
			isEditPeriod: false, // 是否是编辑班期模式（已有班期数据）
			existingPeriodId: null, // 已存在的班期ID
			existingPeriods: [], // 已存在的所有班期数据
			periodIdMap: new Map(), // 班期日期 -> 班期ID 的映射，用于区分新增和更新

			// 申请调用相关
			isApplyCall: false, // 是否是申请调用模式
			sourceMerchantId: '', // 源商家ID
			sourceMerchantType: 1, // 源商家类型（申请调用时使用）
			sourceSkuId: '', // 源SKU ID
			editedProductData: null, // 编辑后的产品数据（申请调用模式）

			// 商家类型
			businessType: 1, // 商家类型：1-一类, 2-二类, 3-三类

			// 产品类型（通过 businessEntry 从缓存获取）
			productType: '', // 产品类型：'1'-泛营地接待(B1), '2'-综合研学业务(B2), '3'-目的地接待(B2), '4'-组团业务(B2调用B1后), '5'-研学活动(B3)


			// 只读模式（从 cooperation 页面跳转过来时，只能查看不能编辑）
			isReadonly: false,

			// 页面标题
			pageTitle: '上架设置',

			// 市场渠道
			salesModeOptions: ['API渠道协作'],
			salesModeIndex: 0,

			// 销售区域
			saleArea: '', // 销售区域字符串，例如：河南省郑州市

			// 接送区域/集散地点（二类商家专用）
			gatherProvince: '', // 省份
			gatherCity: '', // 城市
			gatherDistrict: '', // 区县
			gatherArea: '', // 完整的集散地点
			gatherAreaDisplay: '', // 集散地点显示（地图选择结果）
			regionValue: [], // 省市区选择器值

			// 泛营期设置
			applicationDeadline: 7, // 渠道申请截止天数
			confirmationTime: 3, // 成团确认日期：行程日前

			// 名额设置
			maxPeople: 30, // 单期接团承载人数上限
			minPeople: 10, // 单期单团名额下限
			groupCount: 2, // 每期服务承载最大团数
			// 申请调用模式下的初始值限制（二类商家组团业务）
			initialMaxPeople: null, // 初始每团满员人数（不能超过此值）
			initialMinPeople: null, // 初始最低成团人数（不能小于此值）
			initialGroupCount: null, // 初始每期服务承载最大团数（不能超过此值）- 用于二类组团业务和三类商家
			initialApplicationDeadline: null, // 初始渠道申请截止天数（不能超过此值）

			// 小组设置（二类和三类商家专用）
			groupMaxPeople: 20, // 每小组名额上限
			groupMinPeople: 5, // 每小组名额下限
			maxGroupsPerService: 10, // 每期服务承载最大团数
			groupsCount: 2, // 小组数量（三类商家）

			// 工作人员
			staffList: [

			],
			sourceContactList: [], // 源商家联系人列表（三类商家申请调用时使用）

			// 添加联系人表单相关
			showAddForm: false,
			showStaffPopupForm: false, // 工作人员配置弹窗
			contactTypeOptions: [
				{ label: '请选择类型', value: '' },
				{ label: '报名联系人', value: '报名联系人' },
				{ label: '负责人', value: '负责人' },
				{ label: '客服', value: '客服' },
				{ label: '带队老师', value: '带队老师' },
				{ label: '自定义', value: 'custom' }
			],
			contactTypeIndex: 0, // 当前选中的联系人类型索引
			newStaff: {
				category: '',
				name: '',
				phone: ''
			},

			// 价格设置
			price: '', // 渠道价 (B1) 或 目的地接待服务售价 (B2)
			estimatedPrice: 0, // 预估结算到账- 数字类型
			rate: 0.06, // 手续费率

			// B2价格字段
			destinationServicePrice: 0, // 目的地接待服务售价
			secondServicePrice: '', // 服务售价-渠道（二类商家）
			secondEstimatedPrice: 0, // 预估结算金额（二类商家）
			secondTotalPrice: 0, // 合计售价（二类商家）
			groupAddedServicePrice: '', // 组团增值服务售价
			estimatedGroupSettlement: 0, // 预估增值结算金额
			totalPrice: 0, // 合售售价

			// 三类商家价格字段
			upstreamApiPrice: 0, // 上游及组团服务API渠道售价（就是班期价格）
			escortAServicePrice: '', // 随队A增值服务价格
			escortASettlement: 0, // 随队A服务结算金额

			// 价格说明文本常量
			priceDescriptions: {
				servicePrice1: '备注：* 此处标注的 "服务售价"，指为付费报名参营、参团人员提供本段服务的价格。该价格默认已包含以下两部分费用，相关服务及随团人员无需额外付费：1、本服务项目中涉及的交通、门票、餐饮、住宿等向付费用户提供的全部服务费用；2、下游合作商家派出的跟团工作人员（包括但不限于导师、导游、领队、营长、随队人员、司机等）的相关费用。',
				servicePrice2: '备注：* 此处标注的 "服务售价"，指为付费报名参营、参团人员提供本段服务的价格。该价格默认已包含以下两部分费用，相关服务及人员无需额外付费：1、本服务项目中涉及的交通、门票、餐饮、住宿等向付费用户提供的全部服务费用；2、下游合作商家派出的跟团工作人员（包括但不限于研学导师、随队、司机等）的相关费用。',
				settlementAmount: '扣收软件技术服务费（费率{{ rate * 100 }}%）后的实际到账金额',
				destinationServicePrice: '备注*指目的地接待服务商给出的报价',
				totalPrice1: '指终端消费者预订、购买该服务的价格',
				upstreamApiPrice: '需将上级及组团服务提供的价格传给您留收该人对人起的费用',
				escortServicePrice: '需将增供您随队服务的对人起费用',
				totalPrice2: '需将下得给分销渠道的最终费价'
			},
			// totalPrice: 0, // 合售售价（与二类共用）

			// 协议确认
			agreementChecked: false,

			// 性能优化相关
			priceCalculateTimer: null,
			// 是否展开所有班期（默认横向单行滑动）
			showAllPeriods: false
		}
	},
	computed: {

		// 选中班期价格的整数/小数拆分（固定两位小数）
		selectedPriceParts() {
			const val = Number(this.getSelectedPeriodPrice()) || 0
			const str = val.toFixed(2)
			const parts = str.split('.')
			return { intPart: parts[0], decPart: parts[1] || '00' }
		},

		// 是否可以提交
		canSubmit() {
			return (
				this.agreementChecked &&
				this.staffList.length > 0 &&
				this.selectedPeriodIds.length > 0 &&
				this.validateAllFields()
			)
		},

		// 当前销售模式
		currentSalesMode() {
			return this.salesModeOptions[this.salesModeIndex]
		},

		// 判断是否显示班期管理按钮
		shouldShowManagementBtn() {
			const companyInfo = uni.getStorageSync('companyInfo') || {}
			return companyInfo.businessType === 1 || companyInfo.businessType === 2
		},

		// 格式化的金额显示（保留两位小数）
		formattedEstimatedPrice() {
			return (parseFloat(this.estimatedPrice) || 0).toFixed(2)
		},

		formattedEstimatedGroupSettlement() {
			return (parseFloat(this.estimatedGroupSettlement) || 0).toFixed(2)
		},

		formattedTotalPrice() {
			return (parseFloat(this.totalPrice) || 0).toFixed(2)
		},

		formattedUpstreamApiPrice() {
			// 🔑 如果没有 upstreamApiPrice，则取第一个日期的 secondServicePrice 值
			let price = this.upstreamApiPrice
			console.log('?上游的价格',this.upstreamApiPrice)
			if (!price || price === 0) {
				console.log('this.displayedPeriods',this.displayedPeriods)
				const firstPeriod = this.displayedPeriods && this.displayedPeriods.length > 0 
					? this.displayedPeriods[0] 
					: (this.selectedDates && this.selectedDates.length > 0 ? this.selectedDates[0] : null)
				console.log('firstPeriod',firstPeriod)
				if (firstPeriod) {
					price = firstPeriod.secondServicePrice 
						|| firstPeriod.periodData?.price
				}
			}
			
			// 🔑 如果 price 最后都等于 0，从 A 模式的日期数组第一个中获取 periodData?.price
			const finalPrice = parseFloat(price) || 0
			if (finalPrice === 0) {
				if (this.availablePeriods && this.availablePeriods.length > 0) {
					const firstAPeriod = this.availablePeriods[0]
					// 尝试从多个可能的字段获取价格
					const aPeriodPrice = firstAPeriod.periodData?.price 
						|| firstAPeriod.price 
						|| firstAPeriod.secondServicePrice
						|| firstAPeriod.secondTotalPrice
					if (aPeriodPrice) {
						price = aPeriodPrice
					}
				}
			}
			
			return (parseFloat(price) || 0).toFixed(2)
		},

		formattedEscortASettlement() {
			return (parseFloat(this.escortASettlement) || 0).toFixed(2)
		},

		// 根据商家类型和产品类型返回需要显示的协议列表
		getAgreements() {
			const agreements = []

			// 申请调用模式：与二类商家-组团业务一致
			if (this.isApplyCall) {
				agreements.push('境内研学接团协议')
				agreements.push('境内研学参营协议')
				agreements.push('境内研学随队协议')
				return agreements
			}

			const companyInfo = uni.getStorageSync('companyInfo') || {}
			const businessType = companyInfo.businessType || this.businessType

			// 根据 businessEntry 或 productType 确定实际的产品类型
			let actualProductType = this.productType
			const businessEntry = uni.getStorageSync('businessEntry') || ''

			// 如果 productType 是数字，映射为字符串类型
			if (typeof actualProductType === 'number' || (typeof actualProductType === 'string' && /^\d+$/.test(actualProductType))) {
				const productTypeNum = Number(actualProductType)
				// 1-泛营地接待, 2-综合研学业务, 3-目的地接待, 4-组团业务, 5-研学活动
				if (productTypeNum === 1 || productTypeNum === 3) {
					actualProductType = 'dest_receive'
				} else if (productTypeNum === 2) {
					actualProductType = 'comprehensive_study'
				} else if (productTypeNum === 4) {
					actualProductType = 'group_travel'
				} else if (productTypeNum === 5) {
					actualProductType = 'yanxue'
				}
			}

			// 如果没有 productType，根据 businessEntry 推断
			if (!actualProductType && businessEntry) {
				if (businessEntry === 'dest_receive' || businessEntry === '目的地接待业务' || businessEntry?.includes('目的地接待') || businessEntry?.includes('接待')) {
					actualProductType = 'dest_receive'
				} else if (businessEntry === 'comprehensive_study' || businessEntry === 'comprehensive_research' || businessEntry?.includes('综合研学')) {
					actualProductType = 'comprehensive_study'
				} else if (businessEntry === 'group_travel' || businessEntry?.includes('组团')) {
					actualProductType = 'group_travel'
				} else if (businessEntry === 'yanxue' || businessEntry?.includes('研学')) {
					actualProductType = 'yanxue'
				}
			}

			// 一类商家 - 泛营地接待
			if (businessType === 1) {
				agreements.push('境内研学接团协议')
			}
			// 二类商家
			else if (businessType === 2) {
				// 目的地接待
				if (actualProductType === 'dest_receive') {
					agreements.push('境内研学接团协议')
				}
				// 综合研学业务
				else if (actualProductType === 'comprehensive_study') {
					agreements.push('境内研学参营协议')
					agreements.push('境内研学随队协议')
				}
				// 组团业务
				else if (actualProductType === 'group_travel') {
					agreements.push('境内研学接团协议')
					agreements.push('境内研学参营协议')
					agreements.push('境内研学随队协议')
				}
			}
			// 三类商家 - 研学活动
			else if (businessType === 3) {
				agreements.push('境内研学随队协议')
				agreements.push('境内研学参营协议')
			}

			return agreements
		},

		// 计算符合条件的班期数量（排除灰色禁用的）
		selectablePeriodsCount() {
			if (!this.selectedDates || this.selectedDates.length === 0) {
				return 0
			}
			// 只计算符合条件的班期（isPeriodSelectable 返回 true 的）
			return this.selectedDates.filter(item => this.isPeriodSelectable(item)).length
		},

		// 判断是否为A类日期选择
		// A类日期选择规则：
		// 1. 一类商家（businessType === 1）：所有情况都是A类（productType === 1 泛营地接待）
		// 2. 二类商家（businessType === 2）：
		//    - productType === 2（综合研学业务）：A类
		//    - productType === 3（目的地接待）：A类
		//    - productType === 4（组团业务）：不是A类（B类）
		// 3. 三类商家（businessType === 3）：不是A类（B类）
		// productType说明：1-泛营地接待(B1), 2-综合研学业务(B2), 3-目的地接待(B2), 4-组团业务(B2调用B1后), 5-研学活动(B3)
		isAClassDateSelection() {
			// 一类商家（businessType === 1）：所有情况都是A类
			if (this.businessType === 1) {
				return true
			}
			// 二类商家（businessType === 2）：综合研学业务和目的地接待是A类
			if (this.businessType === 2) {
				// 优先从 productSpu.productType 读取
				let productType = this.productInfo?.mainInfo?.productSpu?.productType
				// 如果 productSpu.productType 不存在（undefined 或 null），再尝试其他来源
				if (productType === undefined || productType === null || productType === '') {
					productType = this.productInfo?.productType || this.productType
				}
				// 转换为数字类型
				let productTypeNum = Number(productType) || 0
				console.log('🔍 isAClassDateSelection - businessType:', this.businessType, 'productType:', productType, 'productTypeNum:', productTypeNum, 'productSpu.productType:', this.productInfo?.mainInfo?.productSpu?.productType)
				// productType === 2（综合研学业务）或 productType === 3（目的地接待）是A类
				return productTypeNum === 2 || productTypeNum === 3
			}
			// 其他情况（二类组团业务、三类商家等）不是A类
			return false
		},

		// 判断当前是A模式还是B模式
		// 从草稿箱进入：只判断 productType
		//   - productType 1, 2, 3 → A模式（泛营地接待、综合研学业务、目的地接待）
		//   - productType 4, 5 → B模式（组团业务、研学活动）
		// 从申请调用进入：根据 productType、businessType 和 businessEntry 的组合判断
		//   - productType=1 且 businessType=2 → 组团业务（B模式）
		//   - productType=3 且 businessType=2 且 businessEntry='dest_receive' → 直接创建目的地接待（A模式）
		//   - productType=3 且 businessType=2 且 businessEntry='group_travel' → 组团业务调用目的地接待（B模式）
		//   - productType=3 且 businessType=3 → 研学活动（B模式）
		isBMode() {
			// 🔑 获取 businessEntry 用于区分直接创建和组团业务调用
			const businessEntry = uni.getStorageSync('businessEntry') || ''

			// 优先从 productInfo 读取，如果没有则使用 this.productType
			let productType = this.productInfo?.mainInfo?.productSpu?.productType || this.productType
			const productTypeNum = Number(productType) || 0
			const businessTypeNum = Number(this.businessType) || 0
			const sourceMerchantTypeNum = Number(this.sourceMerchantType) || 0

			console.log('🔍 isBMode 判断:', {
				isApplyCall: this.isApplyCall,
				productType: productType,
				productTypeNum: productTypeNum,
				businessType: this.businessType,
				businessTypeNum: businessTypeNum,
				sourceMerchantType: this.sourceMerchantType,
				sourceMerchantTypeNum: sourceMerchantTypeNum,
				businessEntry: businessEntry,
				thisProductType: this.productType,
				productInfoProductType: this.productInfo?.mainInfo?.productSpu?.productType
			})

			if (this.isApplyCall) {
				// 申请调用模式：根据 productType、businessType 和 businessEntry 的组合判断

				// 🔑 如果 productType 还没有设置，根据 businessType 和 sourceMerchantType 推断
				if (!productType || productTypeNum === 0) {
					// B2调用B1（businessType=2, sourceMerchantType=1）→ productType='4'（组团业务，B模式）
					if (businessTypeNum === 2 && sourceMerchantTypeNum === 1) {
						console.log('✅ isBMode: productType未设置，根据 businessType=2 且 sourceMerchantType=1 推断 → B模式（组团业务）')
						return true
					}
					// B3调用B2（businessType=3, sourceMerchantType=2）→ productType='5'（研学活动，B模式）
					if (businessTypeNum === 3 && sourceMerchantTypeNum === 2) {
						console.log('✅ isBMode: productType未设置，根据 businessType=3 且 sourceMerchantType=2 推断 → B模式（研学活动）')
						return true
					}
					// 其他情况，默认A模式
					console.log('⚠️ isBMode: productType未设置且无法推断，默认A模式')
					return false
				}

				// productType === 1 且 businessType === 2 → 组团业务（B模式）
				if (productTypeNum === 1 && businessTypeNum === 2) {
					console.log('✅ isBMode: productType=1 且 businessType=2 → B模式')
					return true
				}

				// productType === 3 且 businessType === 2 的情况需要区分：
				if (productTypeNum === 3 && businessTypeNum === 2) {
					// 通过组团业务调用目的地接待产品 → B模式
					if (businessEntry === 'group_travel') {
						console.log('✅ isBMode: 组团业务调用目的地接待产品 → B模式')
						return true  // B模式
					}
					// 直接创建目的地接待 → A模式
					if (businessEntry === 'dest_receive') {
						console.log('✅ isBMode: 直接创建目的地接待 → A模式')
						return false  // A模式
					}
					// 兜底：默认A模式（跨省的目的地研学）
					console.log('⚠️ isBMode: 未匹配到 businessEntry，默认A模式（跨省的目的地研学）')
					return false
				}

				// productType === 3 且 businessType === 3 → 研学活动（B模式）
				if (productTypeNum === 3 && businessTypeNum === 3) {
					console.log('✅ isBMode: productType=3 且 businessType=3 → B模式')
					return true
				}

				// 其他申请调用情况，默认根据 productType 判断
				// productType 4 或 5 为 B 模式，productType 1, 2, 3 为 A 模式
				const result = productTypeNum === 4 || productTypeNum === 5
				console.log('✅ isBMode: 其他申请调用情况，根据 productType 判断 →', result ? 'B模式' : 'A模式')
				return result
			} else {
				// 从草稿箱进入：只判断 productType
				// productType 4 或 5 为 B 模式，productType 1, 2, 3 为 A 模式
				const result = productTypeNum === 4 || productTypeNum === 5
				console.log('✅ isBMode: 非申请调用模式，根据 productType 判断 →', result ? 'B模式' : 'A模式')
				return result
			}
		},

		// 显示的班期列表（只显示在日历中选中的日期）
		// A模式：显示在日历A模式中选中的班期（isSelected: true）
		// B模式：显示在日历B模式中选中的班期（isSelected: true）
		displayedPeriods() {
			if (!this.selectedDates || this.selectedDates.length === 0) {
				console.log('⚠️ displayedPeriods: selectedDates为空')
				return []
			}
			// 只读模式下，只显示可选的班期（过滤掉灰色的不可选班期）
			if (this.isReadonly) {
				const result = this.selectedDates.filter(item => this.isPeriodSelectable(item))
				console.log('⚠️ displayedPeriods: 只读模式，显示', result.length, '个日期')
				return result
			}

			// 只显示在日历中选中的日期（isSelected: true）
			// A模式显示A模式选中的，B模式显示B模式选中的
			const result = this.selectedDates.filter(item => item.isSelected)
			const mode = this.isBMode ? 'B模式' : 'A模式'
			console.log('⚠️ displayedPeriods:', mode, '显示', result.length, '个选中的日期，总日期数:', this.selectedDates.length, '选中的日期:', result.map(r => r.DateName))
			return result
		},

		showGatherSection() {
			return this.businessType !== 1
		},

		// 获取每团满员人数的最大值限制
		maxPeopleLimit() {
			// 获取 productType（优先从 productInfo 读取，否则使用 this.productType）
			let productType = this.productInfo?.mainInfo?.productSpu?.productType || this.productType
			const productTypeNum = Number(productType) || 0
			const businessTypeNum = Number(this.businessType) || 0

			// 组团业务（productType = 1 且 businessType = 2）：不能超过初始值
			if (productTypeNum === 1 && businessTypeNum === 2 && this.initialMaxPeople !== null) {
				return this.initialMaxPeople
			}

			// 申请调用模式（B模式）：不能超过初始值
			if (this.isApplyCall && this.initialMaxPeople !== null) {
				return this.initialMaxPeople
			}
			return CONSTANTS.MAX_PEOPLE
		},

		// 获取最低成团人数的最小值限制
		minPeopleLimit() {
			// 申请调用模式（B模式）：不能低于初始值
			if (this.isApplyCall && this.initialMinPeople !== null) {
				return this.initialMinPeople
			}
			// 获取 productType（优先从 productInfo 读取，否则使用 this.productType）
			let productType = this.productInfo?.mainInfo?.productSpu?.productType || this.productType
			const productTypeNum = Number(productType) || 0
			const businessTypeNum = Number(this.businessType) || 0

			// 组团业务（productType = 1 且 businessType = 2）：不能低于初始值
			if (productTypeNum === 1 && businessTypeNum === 2 && this.initialMinPeople !== null) {
				return this.initialMinPeople
			}
			return CONSTANTS.MIN_GROUP_PEOPLE
		},

		// 获取每期服务承载最大团数的最大值限制（用于二类商家 groupCount）
		groupCountLimit() {
			// 申请调用模式下，如果设置了初始值，则不能超过初始值
			if (this.isApplyCall && this.initialGroupCount !== null) {
				return this.initialGroupCount
			}
			return 20
		},
		// 获取每期服务承载最大团数的最大值限制（用于三类商家 maxGroupsPerService）
		maxGroupsPerServiceLimit() {
			// 三类商家，在调用模式下不能超过初始值
			if (this.isApplyCall && this.businessType === 3 && this.initialGroupCount !== null) {
				return this.initialGroupCount
			}
			return 20
		},

		// 获取渠道申请截止天数的最大值限制
		applicationDeadlineLimit() {
			// 获取 productType（优先从 productInfo 读取，否则使用 this.productType）
			let productType = this.productInfo?.mainInfo?.productSpu?.productType || this.productType
			const productTypeNum = Number(productType) || 0
			const businessTypeNum = Number(this.businessType) || 0

			// 组团业务（productType = 1 且 businessType = 2）：不能超过初始值
			if (productTypeNum === 1 && businessTypeNum === 2 && this.initialApplicationDeadline !== null) {
				return this.initialApplicationDeadline
			}

			// 申请调用模式（B模式）：不能超过初始值
			if (this.isApplyCall && this.initialApplicationDeadline !== null) {
				return this.initialApplicationDeadline
			}
			return CONSTANTS.MAX_APPLICATION_DEADLINE
		}
	},

	watch: {
		// 监听服务价格变化，自动计算预估价格
		price: {
			handler(newVal) {
				if (newVal !== undefined && newVal !== null) {
					this.calculateEstimatedPrice()
				}
			},
			immediate: false
		},

		// 监听工作人员列表变化，自动保存草稿
		staffList: {
			handler() {
				if (this.canSave) {
					this.saveToLocalStorage()
				}
			},
			deep: true
		},

		// 监听 groupCount 变化，确保不超过限制
		groupCount(newVal) {
			if (newVal !== undefined && newVal !== null) {
				const limit = this.groupCountLimit
				const numVal = parseInt(newVal) || 1
				if (numVal > limit) {
					this.$nextTick(() => {
						this.groupCount = limit
						this.showError(`每期服务承载最大团数不能超过 ${limit}`)
					})
				}
			}
		},

		// 监听表单数据变化，自动保存草稿
		applicationDeadline(newVal, oldVal) {
			// 避免初始化时的触发
			if (newVal === oldVal) {
				// 继续执行后续逻辑
			} else {
				// 获取 productType（优先从 productInfo 读取，否则使用 this.productType）
				let productType = this.productInfo?.mainInfo?.productSpu?.productType || this.productType
				const productTypeNum = Number(productType) || 0
				const businessTypeNum = Number(this.businessType) || 0

				// 组团业务（productType = 1 且 businessType = 2）：确保不超过初始值限制
				if (productTypeNum === 1 && businessTypeNum === 2 && this.initialApplicationDeadline !== null) {
					const limit = this.applicationDeadlineLimit
					const numVal = parseInt(newVal) || 0
					if (numVal > limit) {
						this.$nextTick(() => {
							this.applicationDeadline = limit
							uni.showToast({
								title: `渠道申请截止天数不能超过 ${limit}`,
								icon: 'none',
								duration: 2000
							})
						})
						return
					}
				}

				// 申请调用模式（B模式）：确保不超过初始值限制
				if (this.isApplyCall && this.initialApplicationDeadline !== null) {
					const limit = this.applicationDeadlineLimit
					const numVal = parseInt(newVal) || 0
					if (numVal > limit) {
						this.$nextTick(() => {
							this.applicationDeadline = limit
							uni.showToast({
								title: `渠道申请截止天数不能超过 ${limit}`,
								icon: 'none',
								duration: 2000
							})
						})
						return
					}
				}
			}

			// 当 applicationDeadline 改变时，检查并调整 confirmationTime
			const maxConfirmationTime = Math.max(3, this.applicationDeadline - 3)
			if (this.confirmationTime > maxConfirmationTime) {
				this.confirmationTime = maxConfirmationTime
			}

			// 重新评估班期选择状态
			if (this.selectedDates && this.selectedDates.length > 0) {
				// 判断是否为A类日期选择
				const isAClass = this.isAClassDateSelection

				this.selectedDates = this.selectedDates.map(dateItem => {
					let isSelected = false
					// A类日期选择：保持全部选中
					if (isAClass) {
						isSelected = true
					} else if (this.isApplyCall && this.businessType === 2) {
						// 二类商家申请调用模式（组团业务）：保持原选择状态
						isSelected = dateItem.isSelected
					} else {
						// 其他情况：重新评估是否符合条件
						isSelected = this.isPeriodSelectableByDate(dateItem.DateName)
					}
					return {
						...dateItem,
						isSelected: isSelected
					}
				})

				// 更新 selectedPeriodIds
				this.selectedPeriodIds = this.selectedDates.filter(item => item.isSelected).map(item => item.periodId)
			}

			if (this.canSave) {
				this.saveToLocalStorage()
			}
		},


		maxPeople(newVal, oldVal) {
			// 避免初始化时的触发
			if (newVal === oldVal) {
				if (this.canSave) {
					this.saveToLocalStorage()
				}
				return
			}

			const numVal = parseInt(newVal) || 0
			let shouldUpdate = false
			let newValue = numVal

			// 获取 productType（优先从 productInfo 读取，否则使用 this.productType）
			let productType = this.productInfo?.mainInfo?.productSpu?.productType || this.productType
			const productTypeNum = Number(productType) || 0
			const businessTypeNum = Number(this.businessType) || 0

			// 组团业务（productType = 1 且 businessType = 2）：确保不超过初始值限制
			if (productTypeNum === 1 && businessTypeNum === 2 && this.initialMaxPeople !== null) {
				const limit = this.maxPeopleLimit
				if (numVal > limit) {
					newValue = limit
					shouldUpdate = true
					uni.showToast({
						title: `每团满员人数不能超过 ${limit}`,
						icon: 'none',
						duration: 2000
					})
				}
			}

			// 申请调用模式（B模式）：确保不超过初始值限制
			if (!shouldUpdate && this.isApplyCall && this.initialMaxPeople !== null) {
				const limit = this.maxPeopleLimit
				if (numVal > limit) {
					newValue = limit
					shouldUpdate = true
					uni.showToast({
						title: `每团满员人数不能超过 ${limit}`,
						icon: 'none',
						duration: 2000
					})
				}
			}
			// 确保不低于最低成团人数
			if (!shouldUpdate && numVal < this.minPeople) {
				const minValue = Math.max(this.minPeople, CONSTANTS.MIN_PEOPLE)
				newValue = minValue
				shouldUpdate = true
			}

			if (shouldUpdate) {
				this.$nextTick(() => {
					this.maxPeople = newValue
				})
				return
			}

			if (this.canSave) {
				this.saveToLocalStorage()
			}
		},

		minPeople(newVal, oldVal) {
			// 避免初始化时的触发
			if (newVal === oldVal) {
				if (this.canSave) {
					this.saveToLocalStorage()
				}
				return
			}

			const numVal = parseInt(newVal) || 0
			let shouldUpdate = false
			let newValue = numVal

			// 获取 productType（优先从 productInfo 读取，否则使用 this.productType）
			let productType = this.productInfo?.mainInfo?.productSpu?.productType || this.productType
			const productTypeNum = Number(productType) || 0
			const businessTypeNum = Number(this.businessType) || 0

			// 组团业务（productType = 1 且 businessType = 2）：确保不低于初始值限制
			if (productTypeNum === 1 && businessTypeNum === 2 && this.initialMinPeople !== null) {
				const limit = this.minPeopleLimit
				if (numVal < limit) {
					newValue = limit
					shouldUpdate = true
					uni.showToast({
						title: `最低成团人数不能低于 ${limit}`,
						icon: 'none',
						duration: 2000
					})
				}
			}

			// 申请调用模式（B模式）：确保不低于初始值限制
			if (!shouldUpdate && this.isApplyCall && this.initialMinPeople !== null) {
				const limit = this.minPeopleLimit
				if (numVal < limit) {
					newValue = limit
					shouldUpdate = true
					uni.showToast({
						title: `最低成团人数不能低于 ${limit}`,
						icon: 'none',
						duration: 2000
					})
				}
			}
			// 确保不高于每团满员人数
			if (!shouldUpdate && numVal > this.maxPeople) {
				const maxValue = Math.min(this.maxPeople, CONSTANTS.MAX_GROUP_PEOPLE)
				newValue = maxValue
				shouldUpdate = true
			}

			if (shouldUpdate) {
				this.$nextTick(() => {
					this.minPeople = newValue
				})
				return
			}

			if (this.canSave) {
				this.saveToLocalStorage()
			}
		}
	},
	onLoad(options) {
		// 🔑 清空日期选择页面的缓存数据，避免其他班期显示错误数据
		try {
			uni.removeStorageSync('checkedPeriodArr')
			uni.removeStorageSync('selectedDates')
			uni.removeStorageSync('selectedDatesA')
			uni.removeStorageSync('selectedDatesB')
			uni.removeStorageSync('selectedDatesBForPeriodList')
			uni.removeStorageSync('userSelectedPeriodsForB')
			uni.removeStorageSync('existingSelectedDates')
			uni.removeStorageSync('periodSelectParams')
			uni.removeStorageSync('periodList')
			uni.removeStorageSync('outerPeriodList')
			uni.removeStorageSync('bStatePeriodsOriginal')
			console.log('[班期创建] onLoad 已清空日期选择页面的缓存数据')
		} catch (e) {
			console.warn('[班期创建] 清空缓存数据失败:', e)
		}
		
		const id = options.id
		console.log("options", options)
		if (!id) {
			this.showError('缺少产品ID参数')
			return
		}
		this.productId = parseInt(id)

		// 获取商家类型
		const companyInfo = uni.getStorageSync('companyInfo') || { businessType: 1 }
		this.businessType = companyInfo.businessType || 1
		console.log('✅ 当前商家类型:', this.businessType)

		// 从缓存中读取产品类型和业务入口
		const businessEntry = uni.getStorageSync('businessEntry') || ''

		// 🔑 检查是否是通过组团业务调用产品（可以是 productType=1 或 productType=3）
		// 判断条件：businessEntry === 'group_travel' 且 businessType === 2
		// productType 应该从上一页 create/index 获取，不在这里强制设置
		const isGroupBusinessCallDestination =
			businessEntry === 'group_travel' &&
			this.businessType === 2

		// 从 URL 参数、缓存或 businessEntry 中读取 productType
		// 注意：如果是 isGroupBusinessCallDestination，productType 应该已经从 create/index 传递过来了
		if (options.productType) {
			this.productType = options.productType
			console.log('✅ 从URL参数读取 productType:', this.productType)
		} else {
			const storedProductType = uni.getStorageSync('productType')
			if (storedProductType) {
				this.productType = storedProductType
				console.log('✅ 从缓存读取 productType:', this.productType)
			} else if (businessEntry && businessEntry !== 'group_travel') {
				this.productType = businessEntry
				console.log('✅ 从 businessEntry 读取 productType:', this.productType)
			}
		}

		if (isGroupBusinessCallDestination) {
			console.log('✅ 通过组团业务调用产品，productType:', this.productType, '（从上一页获取）')
		}
		console.log('✅ 最终产品类型:', this.productType, '业务入口:', businessEntry, 'isGroupBusinessCallDestination:', isGroupBusinessCallDestination)

		// 检查是否是申请调用模式
		// 🔑 特殊情况：通过组团业务调用目的地接待产品时，也应该识别为申请调用模式
		if (options.isApplyCall === 'true' || isGroupBusinessCallDestination) {
			this.isApplyCall = true
			if (isGroupBusinessCallDestination) {
				console.log('✅ 通过组团业务调用目的地接待产品，自动设置为申请调用模式')
			}
			this.sourcePeriodId = options.sourcePeriodId || ''
			this.sourceMerchantId = options.sourceMerchantId || ''
			this.sourceSkuId = options.sourceSkuId || ''
			this.skuId = options.skuId || ''

			// 接收并验证源商家类型
			let receivedSourceMerchantType = parseInt(options.sourceMerchantType) || 0

			// 🔑 特殊情况：通过组团业务调用产品时，根据 productType 设置 sourceMerchantType
			// productType=1（泛营地接待）→ sourceMerchantType=1（一类商家）
			// productType=3（目的地接待）→ sourceMerchantType=2（二类商家）
			if (isGroupBusinessCallDestination) {
				const productTypeNum = Number(this.productType) || 0
				if (productTypeNum === 1) {
					this.sourceMerchantType = 1
					console.log('✅ 通过组团业务调用泛营地接待产品，设置 sourceMerchantType=1（泛营地接待是一类商家的产品）')
				} else if (productTypeNum === 3) {
					this.sourceMerchantType = 2
					console.log('✅ 通过组团业务调用目的地接待产品，设置 sourceMerchantType=2（目的地接待是二类商家的产品）')
				} else {
					// 兜底：根据 productType 推断
					this.sourceMerchantType = productTypeNum === 1 ? 1 : 2
					console.log('✅ 通过组团业务调用产品，根据 productType 推断 sourceMerchantType:', this.sourceMerchantType)
				}
			}
			// 🔍 重要检查：申请调用时，源商家类型不应该等于当前商家类型
			else if (receivedSourceMerchantType === this.businessType) {
				console.warn('⚠️ periodCreate: 检测到源商家类型与当前商家类型相同！')
				console.warn('⚠️ 当前商家类型:', this.businessType)
				console.warn('⚠️ 传递的源商家类型:', receivedSourceMerchantType)
			} else if (receivedSourceMerchantType > 0) {
				this.sourceMerchantType = receivedSourceMerchantType
			} else {
				console.warn('⚠️ periodCreate: 未传递有效的源商家类型，使用默认值:', this.sourceMerchantType)
			}

			// 🔑 申请调用模式：优先根据businessType和sourceMerchantType自动设置productType
			// B2调用B1（businessType=2, sourceMerchantType=1）→ productType='4'（组团业务）
			// B3调用B2（businessType=3, sourceMerchantType=2）→ productType='5'（研学活动）
			// 🔑 但是，如果是通过组团业务调用（isGroupBusinessCallDestination），productType 应该已经从上一页获取，不要覆盖
			if (!isGroupBusinessCallDestination) {
				if (this.businessType === 2 && this.sourceMerchantType === 1) {
					this.productType = '4' // 组团业务
					console.log('✅ 申请调用模式：B2调用B1，自动设置productType=4（组团业务）')
				} else if (this.businessType === 3 && this.sourceMerchantType === 2) {
					this.productType = '5' // 研学活动
					console.log('✅ 申请调用模式：B3调用B2，自动设置productType=5（研学活动）')
				}
			}

			// 如果URL参数中有productType，优先使用URL参数（覆盖自动设置）
			// 🔑 但是，如果是通过组团业务调用（isGroupBusinessCallDestination），productType 应该已经从上一页获取，不要覆盖
			if (options.productType && !isGroupBusinessCallDestination) {
				this.productType = options.productType
				console.log('✅ 申请调用模式：使用URL参数中的productType:', this.productType)
			}

			// 加载编辑后的产品数据
			try {
				const editedDataStr = uni.getStorageSync('applyCallEditedData')
				if (editedDataStr) {
					this.editedProductData = JSON.parse(editedDataStr)
					console.log('✅ 加载编辑后的产品数据:', this.editedProductData)
					// 使用后清除
					uni.removeStorageSync('applyCallEditedData')
				}
			} catch (e) {
				console.error('❌ 加载编辑后的产品数据失败:', e)
			}

			console.log('✅ 申请调用模式参数:', {
				sourcePeriodId: this.sourcePeriodId,
				sourceMerchantId: this.sourceMerchantId,
				sourceSkuId: this.sourceSkuId,
				sourceMerchantType: this.sourceMerchantType,
				businessType: this.businessType,
				productType: this.productType,
				hasEditedData: !!this.editedProductData
			})

			// 接收从产品详情页传递过来的班期ID和SKU ID（如果有的话）
			if (options.sourcePeriodId) {
				this.sourcePeriodId = options.sourcePeriodId
				console.log('✅ 接收到的班期ID:', this.sourcePeriodId)
			}

			if (options.skuId) {
				this.skuId = options.skuId
				console.log('✅ 接收到的SKU ID:', this.skuId)
			}

			// 申请调用模式：loadPeriods() 将在 initializeData() 中调用，确保 productType 已设置
		} else {
			// 非申请调用模式：从URL参数或缓存中读取产品类型
			if (options.productType) {
				this.productType = options.productType
				uni.setStorageSync('productType', options.productType)
				console.log('从URL接收productType:', this.productType)
			} else {
				// 从缓存中读取productType
				const storedProductType = uni.getStorageSync('productType')
				if (storedProductType) {
					this.productType = storedProductType
					console.log('从缓存读取productType:', this.productType)
				} else {
					// 兼容旧逻辑：从businessEntry读取
					const businessEntry = uni.getStorageSync('businessEntry') || ''
					this.productType = businessEntry
					console.log('从businessEntry读取productType:', this.productType)
				}
			}
		}
		console.log('✅ 最终产品类型:', this.productType)
		console.log('✅ onLoad 完成时的参数:', {
			productType: this.productType,
			businessType: this.businessType,
			isApplyCall: this.isApplyCall,
			sourceMerchantType: this.sourceMerchantType,
			businessEntry: uni.getStorageSync('businessEntry') || ''
		})

		// 🔑 在调用 initializeData 之前，先触发一次 isBMode 计算，确保依赖的数据已设置
		// 使用 $nextTick 确保数据已更新到响应式系统中
		this.$nextTick(() => {
			const isBModeInOnLoad = this.isBMode
			console.log('🔍 onLoad: 调用 initializeData 前，isBMode 状态:', isBModeInOnLoad)
			// 初始化数据（加载产品信息 + 班期数据）
			this.initializeData()
		})
	},

	// 在页面显示时检查是否有选择的日期数据
	onShow() {
		this.loadSelectedDates()
	},

	// 页面隐藏时保存草稿
	onHide() {
		if (this.canSave) {
			this.saveToLocalStorage()
		}
	},

	// 页面卸载时清理
	onUnload() {
		// 清理定时器
		if (this.priceCalculateTimer) {
			clearTimeout(this.priceCalculateTimer)
			this.priceCalculateTimer = null
		}
	},

	methods: {
		toggleAllPeriods() {
			this.showAllPeriods = !this.showAllPeriods
		},
		// 预览产品数据
		previewProduct() {
			try {
				const previewData = this.buildPreviewDataForPreview();
				uni.setStorageSync('previewData', previewData);
				uni.navigateTo({ url: '/public/productInfo/productInfoView' });
			} catch (e) {
				console.error('预览数据构建失败:', e);
				uni.showToast({ title: '预览失败，请稍后重试', icon: 'none' });
			}
		},

		// 组装预览所需的数据（尽量从已加载的数据中取值，缺省用合理默认值）
		buildPreviewDataForPreview() {
			const productName = this.productInfo?.mainInfo?.productSpu?.name || '预览产品';
			// 价格：根据商家类型/模式取一个可展示的值
			let price = 0;
			if (!this.isApplyCall && this.businessType === 1) {
				price = parseFloat(this.price) || 0;
			} else if (!this.isApplyCall && this.businessType === 2) {
				price = parseFloat(this.secondTotalPrice) || 0;
			} else if (this.isApplyCall && this.businessType === 2) {
				price = parseFloat(this.totalPrice) || 0;
			} else if (this.isApplyCall && this.businessType === 3) {
				price = parseFloat(this.totalPrice) || 0;
			}

			const images = (this.productInfo?.mainInfo?.productSku?.images?.length
				? this.productInfo.mainInfo.productSku.images
				: (this.productInfo?.mainInfo?.productSpu?.images || [])).map(img => ({
					url: img.url || img,
					alt: img.alt || ''
				}));

			const productFeatures = this.productInfo?.mainInfo?.productSku?.productFeatures || [];
			const specificItinerary = this.productInfo?.mainInfo?.productSku?.specificItinerary || [];
			const expensesIncluded = this.productInfo?.mainInfo?.productSku?.expensesIncluded || [];
			const expensesExcluded = this.productInfo?.mainInfo?.productSku?.expensesExcluded || '';
			const otherExpenses = this.productInfo?.mainInfo?.productSku?.otherExpenses || '';

			const minYearOld = this.productInfo?.mainInfo?.productSku?.minYearOld || 0;
			const maxYearOld = this.productInfo?.mainInfo?.productSku?.maxYearOld || 0;
			const parentsAccompanied = this.form?.parentsAccompanied ? 1 : 0;

			return {
				productName,
				price,
				images,
				productFeatures,
				specificItinerary,
				expensesIncluded,
				expensesExcluded,
				otherExpenses,
				minYearOld,
				maxYearOld,
				parentsAccompanied
			};
		},

		// 加载产品信息
		async loadProductInfo() {
			this.loading = true
			try {
				const companyInfo = uni.getStorageSync('companyInfo') || {
					businessType: 1
				}
				// 确定使用哪个商家类型来请求产品
				// 申请调用模式：使用源商家类型（产品所属的商家类型）
				// 创建新产品模式：使用当前商家类型
				let merchantType

				const businessEntry = uni.getStorageSync('businessEntry') || ''
				const productTypeNum = Number(this.productType) || 0

				// 🔑 特殊情况：通过组团业务调用产品时，根据 productType 确定 merchantType
				// productType=1（泛营地接待）→ merchantType=1（一类商家）
				// productType=3（目的地接待）→ merchantType=2（二类商家）
				const isGroupBusinessCallDestination = businessEntry === 'group_travel' && this.businessType === 2

				if (isGroupBusinessCallDestination) {
					if (productTypeNum === 1) {
						merchantType = 1
						console.log('📊 periodCreate 加载产品信息（通过组团业务调用泛营地接待产品）:', {
							productId: this.productId,
							requestMerchantType: merchantType,
							reason: '泛营地接待产品是一类商家的产品'
						})
					} else if (productTypeNum === 3) {
						merchantType = 2
						console.log('📊 periodCreate 加载产品信息（通过组团业务调用目的地接待产品）:', {
							productId: this.productId,
							requestMerchantType: merchantType,
							reason: '目的地接待产品是二类商家的产品'
						})
					} else {
						// 兜底：根据 productType 推断
						merchantType = productTypeNum === 1 ? 1 : 2
						console.log('📊 periodCreate 加载产品信息（通过组团业务调用产品，根据 productType 推断）:', {
							productId: this.productId,
							productType: this.productType,
							requestMerchantType: merchantType
						})
					}
				} else if (this.isApplyCall) {
					// 申请调用模式：使用源商家类型
					// 优先使用 this.sourceMerchantType（应该已经在 onLoad 中正确设置）
					// 如果没有设置，则根据 productType 推断：
					//   - productType=1（泛营地接待）→ merchantType=1（一类商家）
					//   - productType=2（综合研学）→ merchantType=2（二类商家）
					//   - productType=3（目的地接待）→ merchantType=2（二类商家）
					//   - productType=4（组团业务）→ merchantType=1（一类商家，因为组团业务是B2调用B1）
					//   - productType=5（研学活动）→ merchantType=2（二类商家，因为研学活动是B3调用B2）
					if (this.sourceMerchantType && this.sourceMerchantType > 0) {
						merchantType = this.sourceMerchantType
					} else {
						// 根据 productType 推断 merchantType
						if (productTypeNum === 1 || productTypeNum === 4) {
							merchantType = 1 // 泛营地接待和组团业务都是一类商家的产品
						} else if (productTypeNum === 2 || productTypeNum === 3 || productTypeNum === 5) {
							merchantType = 2 // 综合研学、目的地接待、研学活动都是二类商家的产品
						} else {
							// 兜底：使用当前商家类型-1（申请调用时，源商家类型通常是当前商家类型-1）
							merchantType = Math.max(1, companyInfo.businessType - 1)
							console.warn('⚠️ 无法确定 merchantType，使用默认值:', merchantType)
						}
					}
					console.log('📊 periodCreate 加载产品信息（申请调用模式）:', {
						productId: this.productId,
						sourceMerchantType: this.sourceMerchantType,
						productType: this.productType,
						currentMerchantType: companyInfo.businessType,
						requestMerchantType: merchantType,
						reason: this.sourceMerchantType && this.sourceMerchantType > 0 ? '使用 sourceMerchantType' : '根据 productType 推断'
					})
				} else {
					// 创建新产品模式：使用当前商家类型
					merchantType = companyInfo.businessType
					console.log('📊 periodCreate 加载产品信息（创建新产品）:', {
						productId: this.productId,
						requestMerchantType: merchantType
					})
				}

				const res = await request({
					url: `/product-spu/getProduct?id=${this.productId}&merchantType=${merchantType}`,
					method: 'GET'
				})

				if (res.code === 200) {
					const productInfo = mergeAllProducts([res.data], merchantType)
					this.productInfo = productInfo[0]
					console.log('✅ 产品信息加载成功:', res.data)

					// 🔑 如果 productType 还没有设置，尝试从产品信息中读取
					// 但是，如果是通过组团业务调用（isGroupBusinessCallDestination），productType 应该已经从上一页获取，不要覆盖
					const businessEntry = uni.getStorageSync('businessEntry') || ''
					const isGroupBusinessCallDestination = businessEntry === 'group_travel' && this.businessType === 2

					if ((!this.productType || this.productType === '') && !isGroupBusinessCallDestination) {
						const productTypeFromInfo = this.productInfo?.productType || this.productInfo?.mainInfo?.productSpu?.productType
						if (productTypeFromInfo) {
							this.productType = productTypeFromInfo
							console.log('✅ 从产品信息中读取 productType:', this.productType)
							// 🔑 强制更新视图，确保 isBMode 和 isAClassDateSelection 计算属性重新计算
							this.$nextTick(() => {
								// 强制触发 isBMode 计算属性的重新计算
								const _ = this.isBMode
								this.$forceUpdate()
							})
						}
					} else if (isGroupBusinessCallDestination) {
						console.log('✅ 通过组团业务调用产品，保持 productType:', this.productType, '（从上一页获取），不从产品信息覆盖')
						// 🔑 即使不覆盖 productType，也要确保 isBMode 计算属性重新计算
						this.$nextTick(() => {
							// 强制触发 isBMode 计算属性的重新计算
							const _ = this.isBMode
							this.$forceUpdate()
						})
					}
				} else {
					this.showError('获取产品信息失败')
				}
			} catch (error) {
				console.error('❌ 获取产品信息失败:', error)
				this.showError('获取产品信息失败')
			} finally {
				this.loading = false
			}
		},

		// 初始化数据加载（产品信息 + 班期数据）
		async initializeData() {
			// 先加载产品信息（确保 productType 已设置）
			await this.loadProductInfo()

			// 🔑 强制触发 isBMode 计算属性的重新计算，确保依赖的数据已设置
			// 通过访问 this.isBMode 来触发计算
			// 使用 $nextTick 确保 productType 等数据已经更新到响应式系统中
			await this.$nextTick()
			const currentIsBMode = this.isBMode
			console.log('✅ initializeData: 当前 isBMode 状态:', currentIsBMode, 'productType:', this.productType, 'businessType:', this.businessType, 'isApplyCall:', this.isApplyCall, 'sourceMerchantType:', this.sourceMerchantType)

			// 申请调用模式：加载源产品的班期信息供选择（第一个接口）
			// 必须在 loadProductInfo() 之后调用，确保 productType 和 isBMode 已正确设置
			if (this.isApplyCall) {
				// 🔑 再次确保 isBMode 正确计算
				await this.$nextTick()
				const isBModeBeforeLoadPeriods = this.isBMode
				console.log('🔍 initializeData: 调用 loadPeriods 前，isBMode 状态:', isBModeBeforeLoadPeriods)
				await this.loadPeriods()
			}

			// 先加载从 dateUtilPage 返回的选中日期（如果有）
			// 这样可以在 loadExistingPeriods 中保留 isSelected 状态
			// 注意：loadSelectedDates 是异步的，但使用 uni.getStorage，需要等待
			await new Promise((resolve) => {
				this.loadSelectedDates()
				// 给一点时间让 loadSelectedDates 完成
				setTimeout(resolve, 100)
			})

			// 无论产品信息加载成功与否，都尝试加载班期数据（第二个接口）
			console.log('✅ 产品信息加载完成，开始查询班期数据，当前 isBMode:', this.isBMode)
			await this.loadExistingPeriods()
		},
		// 加载班期信息（申请调用模式 - 加载源商家的班期供选择）
		async loadPeriods() {
			try {
				const companyInfo = uni.getStorageSync('companyInfo')
				console.log('📊 申请调用模式：加载源商家的班期列表')
				console.log('源商家ID:', this.sourceMerchantId)
				console.log('源商家类型:', this.sourceMerchantType)

				// 申请调用模式：查询源商家的班期（用于选择）
				// 使用源商家ID和源商家类型
				const merchantId = this.sourceMerchantId || companyInfo.id
				const merchantType = this.sourceMerchantType || 1

				const res = await request({
					url: `/period-sku/getPeriodBySpuId?spuId=${this.productId}&merchantId=${merchantId}&businessType=${merchantType}`,
					method: 'GET'
				})

				console.log('✅ 获取源商家班期信息成功:', res)

				if (res.code === 200 && res.data) {
					this.availablePeriods = res.data
					// 从第一个班期数据中获取手续费率
					if (res.data.length > 0 && res.data[0].rate !== undefined) {
						this.rate = res.data[0].rate
					} else {
						this.rate = 0.06 // 默认手续费率 6%
					}
					console.log('手续费率:', this.rate)

					// 调用模式：根据班期数据更新 applicationDeadline
					if (this.isApplyCall && res.data.length > 0) {
						const firstPeriod = res.data[0]

						// 获取 productType（优先从 productInfo 读取，否则使用 this.productType）
						let productType = this.productInfo?.mainInfo?.productSpu?.productType || this.productType
						const productTypeNum = Number(productType) || 0
						const businessTypeNum = Number(this.businessType) || 0

						// 从班期数据中获取 applicationDeadline
						const periodApplicationDeadline = firstPeriod.applicationDeadline
						if (periodApplicationDeadline !== undefined && periodApplicationDeadline !== null) {
							this.applicationDeadline = periodApplicationDeadline
							console.log('✅ 调用模式：已更新 applicationDeadline:', this.applicationDeadline)

							// 🔑 获取 businessEntry 用于区分直接创建和组团业务调用
							const businessEntry = uni.getStorageSync('businessEntry') || '';

							// 组团业务（productType = 1 且 businessType = 2）或通过组团业务调用目的地接待产品：设置初始值限制
							if ((productTypeNum === 1 && businessTypeNum === 2) ||
								(productTypeNum === 3 && businessTypeNum === 2 && businessEntry === 'group_travel' && this.isApplyCall)) {
								this.initialApplicationDeadline = periodApplicationDeadline
								console.log('✅ 组团业务/组团业务调用目的地接待：已设置 initialApplicationDeadline:', this.initialApplicationDeadline)
							}
						}

						// 🔑 获取 businessEntry 用于区分直接创建和组团业务调用
						const businessEntry = uni.getStorageSync('businessEntry') || '';

						// 组团业务（productType = 1 且 businessType = 2）或通过组团业务调用目的地接待产品：设置 maxPeople 初始值限制
						if ((productTypeNum === 1 && businessTypeNum === 2) ||
							(productTypeNum === 3 && businessTypeNum === 2 && businessEntry === 'group_travel' && this.isApplyCall)) {
							const periodMaxPeople = firstPeriod.fullNumberOfPeople
							if (periodMaxPeople !== undefined && periodMaxPeople !== null) {
								this.initialMaxPeople = periodMaxPeople
								this.maxPeople = periodMaxPeople
								console.log('✅ 组团业务/组团业务调用目的地接待：已设置 initialMaxPeople:', this.initialMaxPeople)
							}
						}

						// 申请调用模式：从接口获取的班期数据中设置初始 minPeople 限制
						const periodMinPeople = firstPeriod.leastNumberOfPeople
						if (periodMinPeople !== undefined && periodMinPeople !== null) {
							this.initialMinPeople = periodMinPeople
							this.minPeople = periodMinPeople
							console.log('✅ 申请调用模式 - 从接口获取初始 minPeople (leastNumberOfPeople):', this.initialMinPeople)
						}

						// 申请调用模式：从接口获取的班期数据中设置初始 groupCount 限制
						// 如果班期数据中有 fullNumberOfRegiment，则设置为 initialGroupCount
						if (firstPeriod.fullNumberOfRegiment !== undefined && firstPeriod.fullNumberOfRegiment !== null) {
							this.initialGroupCount = firstPeriod.fullNumberOfRegiment
							this.groupCount = firstPeriod.fullNumberOfRegiment
							console.log('✅ 申请调用模式 - 从接口获取初始 groupCount:', this.initialGroupCount)
						}
						// 三类商家使用 maxGroupsPerService
						if (this.businessType === 3 && firstPeriod.maxGroupsPerService !== undefined && firstPeriod.maxGroupsPerService !== null) {
							this.initialGroupCount = firstPeriod.maxGroupsPerService
							this.maxGroupsPerService = firstPeriod.maxGroupsPerService
							console.log('✅ 三类商家申请调用 - 从接口获取初始 maxGroupsPerService:', this.initialGroupCount)
						}

						// 申请调用模式：自动回显上级服务价格（所有班期价格相同，从第一个班期获取）
						if (firstPeriod.price !== undefined && firstPeriod.price !== null) {
							const periodPrice = firstPeriod.price
							// B2申请调用：自动填充目的地接待服务售价
							if (this.businessType === 2) {
								this.destinationServicePrice = periodPrice
								console.log('✅ B2申请调用 - 自动回显目的地接待服务售价:', this.destinationServicePrice)
								this.calculateType2Prices()
							} else if (this.businessType === 3) {
								// B3申请调用：自动填充上游及组团服务API渠道售价
								this.upstreamApiPrice = periodPrice
								console.log('✅ B3申请调用 - 自动回显上游及组团服务API渠道售价:', this.upstreamApiPrice)
								this.calculateType3Prices()
							}
						}
					}

					// 🔑 申请调用模式：根据模式决定如何处理班期数据
					// B模式：第一个接口的班期作为A状态（可选范围），不直接设置为 selectedDates
					// A模式：第一个接口的班期直接设置为 selectedDates
					// 🔑 强制重新计算 isBMode，确保依赖的数据已设置
					// 使用 $nextTick 确保数据已更新
					await this.$nextTick()
					const currentIsBMode = this.isBMode
					const businessEntry = uni.getStorageSync('businessEntry') || ''
					console.log('🔍 loadPeriods: 当前 isBMode 状态:', currentIsBMode, {
						productType: this.productType,
						productTypeNum: Number(this.productType) || 0,
						businessType: this.businessType,
						businessTypeNum: Number(this.businessType) || 0,
						isApplyCall: this.isApplyCall,
						sourceMerchantType: this.sourceMerchantType,
						sourceMerchantTypeNum: Number(this.sourceMerchantType) || 0,
						businessEntry: businessEntry,
						productInfoProductType: this.productInfo?.mainInfo?.productSpu?.productType
					})

					if (currentIsBMode) {
						// B模式：第一个接口的班期作为A状态（可选范围），保存到 availablePeriods
						// 不调用 convertPeriodsToDateCards()，因为 selectedDates 应该由第二个接口或用户选择决定
						console.log('✅ B模式：第一个接口的班期作为A状态（可选范围），不直接设置为 selectedDates')
						console.log('✅ availablePeriods（A状态可选范围）:', this.availablePeriods.length, '个班期')
					} else {
						// A模式：第一个接口的班期直接设置为 selectedDates
						this.convertPeriodsToDateCards()
						console.log('✅ A模式：第一个接口的班期直接设置为 selectedDates')
					}
				} else {
					// 第一个接口没有返回数据
					console.warn('⚠️ 第一个接口（源商家班期）没有返回数据')
					this.availablePeriods = []
				}
			} catch (error) {
				console.error('❌ 获取源商家班期信息失败:', error)
				this.showError('获取班期信息失败')
			}
		},

		// 加载已存在的班期数据（所有模式 - 查询当前商家对该产品的班期并回显）
		async loadExistingPeriods() {
			try {
				const companyInfo = uni.getStorageSync('companyInfo')
				console.log('📊 查询当前商家对该产品的已有班期数据')
				console.log('当前商家ID:', companyInfo.id)
				console.log('当前商家类型:', companyInfo.businessType)

				const res = await request({
					url: `/period-sku/getPeriodBySpuId?spuId=${this.productId}&merchantId=${companyInfo.id}&businessType=${companyInfo.businessType}`,
					method: 'GET'
				})

				console.log('✅ 查询班期结果2（当前商家）:', res)

				if (res.code === 200 && res.data && res.data.length > 0) {
					// 有班期数据，进入编辑模式
					this.isEditPeriod = true
					this.existingPeriods = res.data

					// 🔑 申请调用模式且是B模式：第二个接口的班期作为B状态（已选中的班期）
					// 第一个接口的班期已经在 availablePeriods 中（A状态可选范围）
					// 🔑 强制重新计算 isBMode，确保依赖的数据已设置
					const currentIsBMode = this.isBMode
					const isBModeApplyCall = this.isApplyCall && currentIsBMode
					console.log('🔍 loadExistingPeriods: 当前 isBMode 状态:', currentIsBMode, 'productType:', this.productType, 'businessType:', this.businessType, 'isApplyCall:', this.isApplyCall, 'isBModeApplyCall:', isBModeApplyCall)
					if (isBModeApplyCall) {
						console.log('✅ B模式：第二个接口的班期作为B状态（已选中的班期）')
					}

					// 取第一个班期的公共配置信息（假设所有班期的配置相同）
					const firstPeriod = res.data[0]
					this.existingPeriodId = firstPeriod.id

					console.log(`✅ 发现 ${res.data.length} 个已有班期，回显到表单`)

					// 回显班期公共配置信息（从第一个班期获取）
					this.applicationDeadline = firstPeriod.applicationDeadline || 15
					this.confirmationTime = firstPeriod.confirmationTime || 15
					this.maxPeople = firstPeriod.fullNumberOfPeople || 30
					this.minPeople = firstPeriod.leastNumberOfPeople || 20
					this.groupCount = firstPeriod.fullNumberOfRegiment || 2
					this.saleArea = firstPeriod.saleArea || ''
					this.rate = firstPeriod.rate || 0.06

					// 申请调用模式：设置初始 minPeople 限制（从接口获取的 leastNumberOfPeople）
					if (this.isApplyCall && firstPeriod.leastNumberOfPeople !== undefined && firstPeriod.leastNumberOfPeople !== null) {
						this.initialMinPeople = firstPeriod.leastNumberOfPeople
						console.log('✅ 编辑模式 - 申请调用：已设置 initialMinPeople:', this.initialMinPeople)
					}

					// 处理 saleArea（省市区选择器的值），如果有值则拆分成省市区
					if (firstPeriod.saleArea && firstPeriod.saleArea.trim()) {
						const saleAreaStr = firstPeriod.saleArea.trim()
						// 匹配格式：XX省XX市XX区 或 XX省XX市XX县
						// 使用正则表达式匹配：省名+省、市名+市、区/县名+区/县
						const match = saleAreaStr.match(/^(.+?省)(.+?市)(.+?[区县])$/)
						if (match) {
							// 匹配成功，提取省、市、区/县
							this.gatherProvince = match[1] // 例如："河北省"
							this.gatherCity = match[2] // 例如："唐山市"
							this.gatherDistrict = match[3] // 例如："路北区"
							this.saleArea = saleAreaStr
							// 更新 regionValue 以便省市区选择器显示
							this.regionValue = [this.gatherProvince, this.gatherCity, this.gatherDistrict]
						} else {
							// 如果匹配失败，尝试其他格式或保持原值
							this.saleArea = saleAreaStr
							// 尝试简单的拆分逻辑（如果原格式不标准）
							// 这里可以根据实际情况添加更多的拆分逻辑
						}
					} else {
						// saleArea 为空或不存在
						this.saleArea = ''
					}

					// 处理 gatherArea（地图地址选择器的值）
					if (firstPeriod.gatherArea && firstPeriod.gatherArea.trim()) {
						this.gatherArea = firstPeriod.gatherArea.trim()
						this.gatherAreaDisplay = firstPeriod.gatherArea.trim()
					} else {
						this.gatherArea = ''
						this.gatherAreaDisplay = ''
					}

					// 回显销售模式
					if (firstPeriod.saleMode) {
						const modeIndex = this.salesModeOptions.indexOf(firstPeriod.saleMode)
						if (modeIndex !== -1) {
							this.salesModeIndex = modeIndex
						}
					}

					// 回显工作人员
					// 三类商家：优先从 teamMembers 读取，否则从 contact 读取
					if (this.businessType === 3 && firstPeriod.teamMembers && Array.isArray(firstPeriod.teamMembers) && firstPeriod.teamMembers.length > 0) {
						this.staffList = firstPeriod.teamMembers.map(c => ({
							category: c.category || '',
							name: c.name || '',
							phone: c.phone || '',
							productType: c.productType !== undefined && c.productType !== null ? Number(c.productType) : (Number(this.productType) || undefined)
						}))
						// 同时保存源商家联系人（如果有）
						if (firstPeriod.contact && Array.isArray(firstPeriod.contact) && firstPeriod.contact.length > 0) {
							this.sourceContactList = firstPeriod.contact.map(c => ({
								category: c.category || '',
								name: c.name || '',
								phone: c.phone || '',
								businessType: c.businessType || this.sourceMerchantType,
								productType: c.productType !== undefined && c.productType !== null ? Number(c.productType) : (Number(this.productType) || undefined)
							}))
						}
					} else if (firstPeriod.contact && Array.isArray(firstPeriod.contact) && firstPeriod.contact.length > 0) {
						this.staffList = firstPeriod.contact.map(c => ({
							category: c.category || '',
							name: c.name || '',
							phone: c.phone || '',
							productType: c.productType !== undefined && c.productType !== null ? Number(c.productType) : (Number(this.productType) || undefined)
						}))
					}

					// 回显小组设置
					if (firstPeriod.groupMaxPeople) {
						this.groupMaxPeople = firstPeriod.groupMaxPeople
					}
					if (firstPeriod.groupMinPeople) {
						this.groupMinPeople = firstPeriod.groupMinPeople
					}
					if (firstPeriod.maxGroupsPerService) {
						this.maxGroupsPerService = firstPeriod.maxGroupsPerService
					}

					// 回显价格信息（从第一个班期获取）
					if (this.businessType === 1) {
						// 一类商家
						this.price = firstPeriod.price || 0
						this.estimatedPrice = firstPeriod.estimatedPrice || 0
					} else if (this.businessType === 2) {
						// 二类商家
						this.secondServicePrice = firstPeriod.secondServicePrice || 0
						this.secondEstimatedPrice = firstPeriod.secondEstimatedPrice || 0
						this.secondTotalPrice = firstPeriod.secondTotalPrice || 0
					} else if (this.businessType === 3) {
						// 三类商家
						this.upstreamApiPrice = firstPeriod.thirdServicePrice || 0
						this.escortAServicePrice = firstPeriod.thirdAddedServicePrice || 0
						this.escortASettlement = firstPeriod.thirdEstimatedPrice || 0
						this.totalPrice = firstPeriod.totalPrice || 0
					}

					// 回显所有班期日期
					// 🔑 如果已经有从 dateUtilPage 加载的 selectedDates，保留其 isSelected 状态
					// 建立两个映射：日期 -> isSelected，periodId -> isSelected
					const existingSelectedDatesMap = new Map(); // 日期 -> isSelected
					const existingSelectedPeriodIdsMap = new Map(); // periodId -> isSelected
					if (this.selectedDates && this.selectedDates.length > 0) {
						this.selectedDates.forEach(item => {
							// 通过日期匹配
							if (item.DateName) {
								existingSelectedDatesMap.set(item.DateName, item.isSelected);
							}
							// 🔑 通过 periodId 匹配（优先使用 periodId，更准确）
							if (item.periodId || item.id) {
								const periodId = item.periodId || item.id;
								existingSelectedPeriodIdsMap.set(String(periodId), item.isSelected);
								console.log('✅ 保存从 dateUtilPage 返回的选中状态 - periodId:', periodId, 'isSelected:', item.isSelected);
							}
						});
					}

					// 🔑 B模式：第二个接口的班期作为B状态（已选中的班期），全部设置为 isSelected = true
					// 在B模式下，只添加B状态的班期到 selectedDates，不添加A状态的班期
					const mappedPeriods = res.data.map(period => {
						if (!period.availableDate) {
							console.warn('班期缺少日期信息:', period)
							return null
						}

						const { yearDate, monthDate, dayDate, weekDate } = period.availableDate
						const dateStr = `${yearDate}-${monthDate.padStart(2, '0')}-${dayDate.padStart(2, '0')}`

						// 建立日期 -> 班期ID 的映射
						this.periodIdMap.set(dateStr, period.id)

						// 根据商家类型确定显示的价格
						let displayPrice = 0
						if (this.businessType === 1) {
							displayPrice = period.price || 0
						} else if (this.businessType === 2) {
							// 二类商家：显示合计售价
							displayPrice = period.secondTotalPrice || 0
						} else if (this.businessType === 3) {
							displayPrice = period.totalPrice || 0
						}

						// 🔑 申请调用模式且是B模式：第二个接口的班期应该全部设置为 isSelected = true（B状态）
						// 其他情况：根据已有状态或 productType 判断
						let isSelected = false;

						if (isBModeApplyCall) {
							// B模式：第二个接口的班期作为B状态（已选中的班期），全部设置为选中
							isSelected = true;
							console.log('✅ B模式：第二个接口的班期', dateStr, '设置为B状态（已选中）')
						} else if (existingSelectedPeriodIdsMap.has(String(period.id))) {
							// 🔑 优先通过 periodId 匹配（更准确，对应接口返回的初始数据）
							const savedIsSelected = existingSelectedPeriodIdsMap.get(String(period.id));
							// 确保是布尔值
							isSelected = savedIsSelected === true || savedIsSelected === 'true' || savedIsSelected === 1 || savedIsSelected === '1';
							console.log('✅ 通过 periodId 匹配到从 dateUtilPage 返回的选中状态 - periodId:', period.id, 'isSelected:', isSelected);
						} else if (existingSelectedDatesMap.has(dateStr)) {
							// 🔑 如果 periodId 匹配失败，通过日期匹配（兜底）
							const savedIsSelected = existingSelectedDatesMap.get(dateStr);
							// 确保是布尔值
							isSelected = savedIsSelected === true || savedIsSelected === 'true' || savedIsSelected === 1 || savedIsSelected === '1';
							console.log('✅ 通过日期匹配到从 dateUtilPage 返回的选中状态 - dateStr:', dateStr, 'isSelected:', isSelected);
						} else {
							// 如果没有保存的状态，判断是否是从草稿箱进入的 A 类
							// 从草稿箱进入：只判断 productType
							// A类：productType 1, 2, 3（泛营地接待、综合研学业务、目的地接待）
							if (!this.isApplyCall) {
								// 从草稿箱进入：根据 productType 判断是否为 A 类
								let productType = this.productInfo?.mainInfo?.productSpu?.productType || this.productType;
								const productTypeNum = Number(productType) || 0;
								// A类：productType 1, 2, 3，默认全部选中
								if (productTypeNum === 1 || productTypeNum === 2 || productTypeNum === 3) {
									isSelected = true;
								}
							}
						}

						return {
							DateName: dateStr,
							WeekName: weekDate,
							periodId: period.id,
							isSelected: isSelected,
							periodData: {
								price: displayPrice,
								leastNumberOfPeople: period.leastNumberOfPeople,
								fullNumberOfPeople: period.fullNumberOfPeople,
								inventory: period.inventory,
								saleArea: period.saleArea,
								applicationDeadline: period.applicationDeadline
							}
						}
					}).filter(item => item !== null)

					// 🔑 B模式：只添加B状态的班期（isSelected=true）到 selectedDates，不添加A状态的班期
					// 在B模式下，availablePeriods 中的班期（A状态）不应该出现在 selectedDates 中
					if (isBModeApplyCall) {
						// B模式：只添加B状态的班期
						this.selectedDates = mappedPeriods.filter(item => item.isSelected)
						console.log('✅ B模式：第二个接口的班期，只添加B状态的班期到 selectedDates，共', this.selectedDates.length, '个')
					} else {
						// A模式或其他情况：添加所有班期
						this.selectedDates = mappedPeriods
					}

					this.selectedPeriodIds = this.selectedDates.filter(item => item.isSelected).map(item => item.periodId || item.id).filter(id => id);

					// 创建班期列表
					this.createPeriodList(this.selectedDates)

					uni.showToast({
						title: `已加载${this.selectedDates.length}个班期`,
						icon: 'success',
						duration: 1500
					})
				} else {
					console.log('✅ 未发现班期数据，新建模式')
					this.isEditPeriod = false
					this.existingPeriods = []
					this.periodIdMap.clear()

					// 🔑 申请调用模式且是B模式：第二个接口没有数据时，selectedDates 应该为空
					// 第一个接口的班期已经在 availablePeriods 中（A状态可选范围），不应该设置为 selectedDates
					if (this.isApplyCall && this.isBMode) {
						console.log('✅ B模式：第二个接口没有数据，保持 selectedDates 为空')
						console.log('✅ availablePeriods（A状态可选范围）:', this.availablePeriods.length, '个班期')
						// 确保 selectedDates 为空，不被第一个接口的数据覆盖
						if (this.selectedDates.length > 0 && this.selectedDates.some(item => item.periodId && String(item.periodId).startsWith('period_'))) {
							// 如果 selectedDates 中有来自 convertPeriodsToDateCards 的数据（临时ID），清空
							console.log('✅ 清空来自第一个接口的临时 selectedDates 数据')
							this.selectedDates = []
							this.selectedPeriodIds = []
						}
					}
				}
			} catch (error) {
				console.error('❌ 查询班期数据失败:', error)
				// 查询失败不影响继续操作，按新建模式处理
				console.log('✅ 查询失败，按新建模式处理')
				this.isEditPeriod = false
				this.existingPeriods = []
				this.periodIdMap.clear()

				// 🔑 申请调用模式且是B模式：第二个接口失败时，确保 selectedDates 为空
				// 第一个接口的班期已经在 availablePeriods 中（A状态可选范围），不应该设置为 selectedDates
				if (this.isApplyCall && this.isBMode) {
					console.log('✅ B模式：第二个接口失败，保持 selectedDates 为空')
					console.log('✅ availablePeriods（A状态可选范围）:', this.availablePeriods.length, '个班期')
					// 确保 selectedDates 为空，不被第一个接口的数据覆盖
					if (this.selectedDates.length > 0 && this.selectedDates.some(item => item.periodId && String(item.periodId).startsWith('period_'))) {
						// 如果 selectedDates 中有来自 convertPeriodsToDateCards 的数据（临时ID），清空
						console.log('✅ 清空来自第一个接口的临时 selectedDates 数据')
						this.selectedDates = []
						this.selectedPeriodIds = []
					}
				}

				// 不显示错误提示，因为产品没有班期是正常情况
				// 只有在真正需要班期数据时才显示错误
			}
		},

		// 加载选择的日期
		loadSelectedDates() {
			// 先检查是否有B状态的日期（二类组团业务）
			let selectedDatesB = []
			try {
				const selectedDatesBStr = uni.getStorageSync('selectedDatesBForPeriodList')
				if (selectedDatesBStr) {
					selectedDatesB = JSON.parse(selectedDatesBStr)
					// 读取后清除
					uni.removeStorageSync('selectedDatesBForPeriodList')
				}
			} catch (e) {
				console.error('❌ 读取B状态日期失败:', e)
			}

			uni.getStorage({
				key: 'selectedDates',
				success: res => {
					if (res.data) {
						try {
							const selectedDates = JSON.parse(res.data)
							if (selectedDates && selectedDates.length > 0) {
								// 🔑 直接使用 isBMode 计算属性，确保逻辑一致
								const isBMode = this.isBMode
								if (isBMode) {
									// B模式：只保留B状态的班期（isSelected=true 的），过滤掉A状态的班期
									// 二类组团业务或三类商家：优先使用 selectedDates 中已有的 isSelected 属性
									// 如果 selectedDates 中已经有 isSelected 属性，直接使用；否则根据 selectedDatesB 判断
									this.selectedDates = selectedDates.map((dateItem, index) => {
										// 检查 dateItem 的所有属性
										const hasIsSelected = dateItem.hasOwnProperty('isSelected')
										const isSelectedValue = dateItem.isSelected

										// 如果 dateItem 中已经有 isSelected 属性，优先使用（从 dateUtilPage 返回的数据）
										if (hasIsSelected && (isSelectedValue === true || isSelectedValue === 'true')) {
											return {
												...dateItem,
												isSelected: true
											}
										} else if (selectedDatesB && selectedDatesB.length > 0) {
											// 如果没有 isSelected 属性，根据B状态的日期判断
											// 确保日期格式一致（都是字符串）
											const dateName = String(dateItem.DateName || '')
											const isSelected = selectedDatesB.some(bDate => String(bDate) === dateName)
											return {
												...dateItem,
												isSelected: isSelected
											}
										} else {
											// 如果既没有 isSelected 属性，也没有 selectedDatesB，默认不选中
											return {
												...dateItem,
												isSelected: false
											}
										}
									}).filter(item => item.isSelected) // 🔑 B模式：只保留 isSelected=true 的班期，过滤掉A状态的班期

									console.log('✅ B模式：过滤后只保留B状态的班期，共', this.selectedDates.length, '个')
								} else {
									// A模式：一类商家、二类目的地研学、综合研学
									// 判断是否为A类日期选择
									const isAClass = this.isAClassDateSelection

									this.selectedDates = selectedDates.map((dateItem, index) => {
										// 检查 dateItem 的所有属性
										const hasIsSelected = dateItem.hasOwnProperty('isSelected')
										const isSelectedValue = dateItem.isSelected
										const hasIs = dateItem.hasOwnProperty('is')
										const isValue = dateItem.is

										// 如果 dateItem 中已经有 isSelected 属性，优先使用
										if (hasIsSelected) {
											// A类日期选择：强制选中
											if (isAClass) {
												return {
													...dateItem,
													isSelected: true
												}
											}
											// 非A类：使用已有的 isSelected 值
											const finalIsSelected = isSelectedValue === true || isSelectedValue === 'true' || isSelectedValue === 1 || isSelectedValue === '1'
											return {
												...dateItem,
												isSelected: finalIsSelected
											}
										}
										// 如果没有 isSelected 属性，但有 is 属性，使用 is 属性
										if (hasIs && (isValue === true || isValue === 'true' || isValue === 1 || isValue === '1')) {
											return {
												...dateItem,
												isSelected: true
											}
										}
										// 否则按原有逻辑处理
										let isSelected = false
										if (isAClass) {
											// A类日期选择：默认全部选中
											isSelected = true
										} else if (this.isApplyCall) {
											// 申请调用模式：不默认勾选，需要用户手动选择
											isSelected = false
										} else {
											// 创建新产品模式：符合条件的默认勾选
											isSelected = this.isPeriodSelectableByDate(dateItem.DateName)
										}
										return {
											...dateItem,
											isSelected: isSelected
										}
									})
								}

								// 更新 selectedPeriodIds
								this.selectedPeriodIds = this.selectedDates.filter(item => item.isSelected).map(item => item.periodId || item.id)

								this.createPeriodList(this.selectedDates)

								// 强制更新视图，确保样式正确应用
								this.$nextTick(() => {
									this.$forceUpdate()
								})

								// 获取后清空storage，避免重复获取
								uni.removeStorageSync('selectedDates')
							}
						} catch (e) {
							console.error('解析日期数据失败:', e)
						}
					}
				},
				fail: err => {
					console.error('获取日期数据失败:', err)
				}
			})
		},

		// 创建班期
		async createPeriod(periodData) {
			try {
				// 如果是数组，逐个创建
				if (Array.isArray(periodData)) {
					const results = []
					for (const period of periodData) {
						const res = await request({
							url: '/period-sku/create',
							method: 'POST',
							data: period, // 单个班期对象
							loading: true
						})

						if (res.code === 200) {
							results.push(res.data)
						} else {
							throw new Error(res.message || '创建班期失败')
						}
					}
					return { data: results }
				} else {
					// 单个班期
					const res = await request({
						url: '/period-sku/create',
						method: 'POST',
						data: periodData,
						loading: true
					})

					if (res.code === 200) {
						return res.data
					} else {
						throw new Error(res.message || '创建班期失败')
					}
				}
			} catch (error) {
				console.error('创建班期失败:', error)
				throw error
			}
		},

		// 更新班期
		async updatePeriod(periodId, periodData) {
			try {
				console.log('📝 更新班期，ID:', periodId, '数据:', periodData)
				const res = await request({
					url: `/period-sku/update?id=${periodId}`,
					method: 'PUT',
					data: periodData,
					loading: true
				})

				if (res.code === 200) {
					console.log('✅ 班期更新成功')
					return res.data
				} else {
					throw new Error(res.message || '更新班期失败')
				}
			} catch (error) {
				console.error('❌ 更新班期失败:', error)
				throw error
			}
		},

		// 返回上一页
		goBack() {
			// 保存草稿
			this.saveDraft()
			uni.navigateBack({
				delta: 1
			})
		},

		// 选择日期
		chooseDate() {
			console.log('=== chooseDate 方法开始执行 ===');
			console.log('this.selectedDates:', this.selectedDates);
			console.log('this.businessType:', this.businessType);
			console.log('this.productType:', this.productType);
			console.log('this.isReadonly:', this.isReadonly);
			console.log('this.isApplyCall:', this.isApplyCall);

			try {
				// 将当前选中的日期，保存到storage，供日期选择页面读取
				if (this.selectedDates && this.selectedDates.length > 0) {
					console.log('保存已选日期供日期选择页读取:', this.selectedDates);
					uni.setStorageSync('existingSelectedDates', JSON.stringify(this.selectedDates));
				}
				console.log('步骤1: 保存已选日期完成');

				// 获取产品类型（可能是字符串或数字，统一转换为数字）
				let productType = this.productType || this.productInfo?.productType || this.productInfo?.mainInfo?.productSpu?.productType || 0
				// 如果是字符串，转换为数字
				if (typeof productType === 'string') {
					productType = parseInt(productType) || 0
				}
				productType = Number(productType) || 0

				console.log('跳转班期管理 - businessType:', this.businessType, 'productType:', productType, 'isApplyCall:', this.isApplyCall)
				console.log('步骤2: 获取产品类型完成');

				// 传递必要参数到 dateUtilPage
				console.log('步骤3: 开始保存参数到 storage');
				uni.setStorageSync('periodSelectParams', JSON.stringify({
					businessType: this.businessType,
					isApplyCall: this.isApplyCall,
					applicationDeadline: this.applicationDeadline,
					productId: this.productId,
					productType: productType,
					allowEdit: true // 从上架设置页面进入，允许编辑日期
				}));
				console.log('步骤3: 保存参数完成');

				// 根据业务类型和产品类型判断如何传递班期数据
				// 一类商家的泛营期设置（businessType=1, productType=1）
				// 二类商家的综合研学（businessType=2, productType=2）与目的地接待（businessType=2, productType=3）
				// -> 所有营期直接显示为A状态，没有B状态
				// 🔑 但是，如果通过组团业务调用目的地接待产品（businessEntry='group_travel'），需要使用B模式逻辑
				console.log('步骤4: 开始判断业务类型和产品类型');

				// 🔑 获取 businessEntry 用于区分直接创建和组团业务调用
				const businessEntry = uni.getStorageSync('businessEntry') || ''
				console.log('步骤4.0: businessEntry:', businessEntry);

				// 判断是否是直接创建目的地接待（A模式）
				const isDirectCreateDestination =
					this.businessType === 2 &&
					productType === 3 &&
					businessEntry === 'dest_receive' &&
					!this.isApplyCall;

				// 判断是否是通过组团业务调用产品（B模式）
				// 注意：可以是 productType=1（泛营地接待）或 productType=3（目的地接待）
				const isGroupBusinessCallDestination =
					this.businessType === 2 &&
					businessEntry === 'group_travel' &&
					this.isApplyCall &&
					(productType === 1 || productType === 3);

				console.log('步骤4.1: isDirectCreateDestination:', isDirectCreateDestination);
				console.log('步骤4.2: isGroupBusinessCallDestination:', isGroupBusinessCallDestination);

				if ((this.businessType === 1 && productType === 1) ||
					(this.businessType === 2 && productType === 2) ||
					isDirectCreateDestination) {
					// 传递所有班期作为A状态
					const periodList = this.selectedDates || []
					uni.setStorageSync('periodList', JSON.stringify(periodList))
					console.log('传递班期列表（A状态）:', periodList)
				}
				// 🔑 通过组团业务调用目的地接待产品，使用B模式逻辑
				else if (isGroupBusinessCallDestination) {
					console.log('步骤4.3: 通过组团业务调用目的地接待产品 → 使用B模式逻辑');

					// 🔑 B模式：第一个接口的班期（availablePeriods）作为A状态（外层班期列表）
					// 将 availablePeriods 转换为日期格式
					let outerPeriodList = []
					if (this.availablePeriods && this.availablePeriods.length > 0) {
						outerPeriodList = this.availablePeriods.map(period => {
							if (!period.availableDate) {
								return null
							}
							const { yearDate, monthDate, dayDate, weekDate } = period.availableDate
							const dateStr = `${yearDate}-${monthDate.padStart(2, '0')}-${dayDate.padStart(2, '0')}`
							return {
								DateName: dateStr,
								WeekName: weekDate,
								periodId: period.id,
								isSelected: false // A状态默认不选中
							}
						}).filter(item => item !== null)
					}
					console.log('步骤4.4: outerPeriodList（A状态，来自第一个接口）:', outerPeriodList);

					// 选中的班期作为B状态（当前班期列表）
					// 如果第二个接口有数据，使用第二个接口的数据；否则使用 selectedDates 中已选中的
					const currentPeriodList = Array.isArray(this.selectedDates)
						? this.selectedDates.filter(item => item && item.isSelected)
						: []
					console.log('步骤4.5: currentPeriodList（B状态）:', currentPeriodList);

					console.log('组团业务调用目的地接待 - 外层班期列表（A状态，来自第一个接口）:', outerPeriodList.length, '个')
					console.log('组团业务调用目的地接待 - 当前班期列表（B状态）:', currentPeriodList.length, '个')

					uni.setStorageSync('outerPeriodList', JSON.stringify(outerPeriodList))
					uni.setStorageSync('periodList', JSON.stringify(currentPeriodList))
					console.log('步骤4.6: 保存班期列表完成');
				}
				// 二类的组团业务（businessType=2, productType=4）
				// 三类的研学活动（businessType=3, productType=5）
				// -> 营期列表显示的日期为A状态，选中的为B状态
				else if ((this.businessType === 2 && productType === 4) ||
					(this.businessType === 3 && productType === 5)) {
					console.log('步骤4.1: 进入二类组团业务或三类研学活动分支');
					// 所有班期作为A状态（外层班期列表）
					const outerPeriodList = Array.isArray(this.selectedDates) ? this.selectedDates : []
					console.log('步骤4.2: outerPeriodList:', outerPeriodList);
					// 选中的班期作为B状态（当前班期列表）
					const currentPeriodList = Array.isArray(this.selectedDates)
						? this.selectedDates.filter(item => item && item.isSelected)
						: []
					console.log('步骤4.3: currentPeriodList:', currentPeriodList);

					console.log('二类组团业务 - 外层班期列表（A状态）:', outerPeriodList)
					console.log('二类组团业务 - 当前班期列表（B状态）:', currentPeriodList)

					uni.setStorageSync('outerPeriodList', JSON.stringify(outerPeriodList))
					uni.setStorageSync('periodList', JSON.stringify(currentPeriodList))
					console.log('步骤4.4: 保存班期列表完成');
				}
				// 其他情况：默认传递所有班期作为A状态
				else {
					const periodList = this.selectedDates || []
					uni.setStorageSync('periodList', JSON.stringify(periodList))
					console.log('默认传递班期列表（A状态）:', periodList)
				}
				console.log('步骤4: 判断业务类型完成');

				// 🔑 如果是申请调用模式且是B模式，传递第一个接口的班期作为可选范围
				// 如果是二类组团业务或三类商家，传递已选中的日期（只允许从这些日期中选择）
				console.log('步骤5: 开始处理 allowedSelectDates');

				// 🔑 通过组团业务调用目的地接待产品（B模式）：第一个接口的班期作为可选范围
				if (isGroupBusinessCallDestination) {
					// 将 availablePeriods 转换为日期字符串数组
					const allowedDates = []
					if (this.availablePeriods && this.availablePeriods.length > 0) {
						this.availablePeriods.forEach(period => {
							if (period.availableDate) {
								const { yearDate, monthDate, dayDate } = period.availableDate
								const dateStr = `${yearDate}-${monthDate.padStart(2, '0')}-${dayDate.padStart(2, '0')}`
								allowedDates.push(dateStr)
							}
						})
					}
					if (allowedDates.length > 0) {
						uni.setStorageSync('allowedSelectDates', JSON.stringify(allowedDates));
						console.log('✅ B模式：第一个接口的班期作为可选范围（allowedSelectDates）:', allowedDates.length, '个日期')
					}
				}
				// 其他申请调用模式或三类商家
				else if ((this.isApplyCall && this.businessType === 2) || this.businessType === 3) {
					if (Array.isArray(this.selectedDates) && this.selectedDates.length > 0) {
						const selectedDateStrings = this.selectedDates
							.filter(item => item && item.isSelected && item.DateName)
							.map(item => item.DateName);
						if (selectedDateStrings.length > 0) {
							uni.setStorageSync('allowedSelectDates', JSON.stringify(selectedDateStrings));
						}
					}
				}
				console.log('步骤5: 处理 allowedSelectDates 完成');

				// 跳转到日期选择页面
				console.log('步骤6: 准备跳转到日期选择页面...');
				uni.navigateTo({
					url: '/public/dateUtilPage/dateUtilPage',
					success: () => {
						console.log('跳转成功');
					},
					fail: (err) => {
						console.error('跳转失败:', err);
						uni.showToast({
							title: '跳转失败，请重试',
							icon: 'none'
						});
					}
				});
				console.log('步骤6: navigateTo 调用完成');
			} catch (error) {
				console.error('chooseDate 方法执行异常:', error);
				console.error('错误堆栈:', error.stack);
				uni.showToast({
					title: '操作异常，请重试',
					icon: 'none'
				});
			}
			console.log('=== chooseDate 方法执行结束 ===');
		},

		// 班期管理（原有方法保留，用于向后兼容）
		managePeriods() {
			// 获取当前已选中的日期
			const selectedDatesData = this.selectedDates || [];

			// 将选中的日期保存到 storage 中，供 dateUtilPage 使用
			if (selectedDatesData.length > 0) {
				uni.setStorageSync('existingSelectedDates', JSON.stringify(selectedDatesData));
			}

			uni.navigateTo({
				url: '/public/dateUtilPage/dateUtilPage'
			})
		},

		// 处理DateCard组件的日期选择事件
		dateChange(selectedDates) {
			if (selectedDates && selectedDates.length > 0) {
				this.selectedDates = selectedDates
				this.createPeriodList(selectedDates)
			}
		},

		// 创建班期列表
		createPeriodList(dates) {
			const companyInfo = uni.getStorageSync('companyInfo') || {
				id: 1
			}

			this.periodList = dates.map((dateItem, index) => {
				const dateParts = dateItem.DateName.split('-')

				// 为每个日期生成唯一的 periodId（如果不存在）
				if (!dateItem.periodId) {
					dateItem.periodId = `temp_${Date.now()}_${index}`
				}

				return {
					periodSku: {
						spuId: this.productId,
						availableDate: {
							yearDate: dateParts[0],
							monthDate: dateParts[1],
							dayDate: dateParts[2],
							weekDate: dateItem.WeekName
						},
						merchantId: companyInfo.id,
						applicationDeadline: 0,
						confirmationTime: 0,
						price: 0,
						fullNumberOfPeople: 0,
						leastNumberOfPeople: 0,
						fullNumberOfRegiment: 0,
						contact: [],
						status: 0,
						inventory: 0,
						saleArea: ''
					}
				}
			})
		},

		// 处理选择器变化
		handlePickerChange(e) {
			const type = e.currentTarget.dataset.type
			const value = e.detail.value

			if (type === 'salesMode') {
				this.salesModeIndex = value
			}
		},

		// 调整数字输入
		adjustNumber(field, delta) {
			const limits = {
				applicationDeadline: [CONSTANTS.MIN_APPLICATION_DEADLINE, this.applicationDeadlineLimit],
				confirmationTime: [3, Math.max(3, this.applicationDeadline - 3)], // 成团确认日期：3到(渠道申请截止天数-3)
				maxPeople: [CONSTANTS.MIN_PEOPLE, this.maxPeopleLimit],
				minPeople: [this.minPeopleLimit, CONSTANTS.MAX_GROUP_PEOPLE],
				groupCount: [1, this.groupCountLimit], // 每期服务承载最大团数：1-20团
				groupMaxPeople: [6, 20], // 每小组名额上限：6-20人
				groupMinPeople: [5, 8], // 每小组名额下限：5-8人
				maxGroupsPerService: [1, this.maxGroupsPerServiceLimit] // 每期服务承载最大团数：1-20团（三类商家调用模式下受限制）
			}

			const [min, max] = limits[field] || [0, 999]
			const currentValue = this[field]
			const newValue = currentValue + delta

			if (newValue >= min && newValue <= max) {
				// 当调整 maxPeople（每团满员人数）时，确保它不能低于 minPeople（最低成团人数）
				if (field === 'maxPeople' && newValue < this.minPeople) {
					this.showError('每团满员人数不能低于最低成团人数')
					return
				}
				// 当调整 minPeople（最低成团人数）时，确保它不能高于 maxPeople（每团满员人数）
				if (field === 'minPeople' && newValue > this.maxPeople) {
					this.showError('最低成团人数不能高于每团满员人数')
					return
				}
				this[field] = newValue
			}
		},

		// 处理 applicationDeadline 输入变化
		handleApplicationDeadlineInput(e) {
			// v-model.number 会自动转换，但这里确保值是数字类型
			// watcher 会自动触发，所以这里不需要额外操作
			// 但为了确保值被正确转换，我们可以在这里做一些处理
			const value = parseFloat(e.detail.value) || 0
			const min = CONSTANTS.MIN_APPLICATION_DEADLINE
			const max = this.applicationDeadlineLimit
			// 确保值在有效范围内
			if (value < min) {
				this.applicationDeadline = min
			} else if (value > max) {
				this.applicationDeadline = max
			} else {
				this.applicationDeadline = value
			}
		},

		// 验证数字输入
		validateNumber(field) {
			// 申请调用模式（二类商家组团业务）：应用初始值限制
			const limits = {
				applicationDeadline: [CONSTANTS.MIN_APPLICATION_DEADLINE, this.applicationDeadlineLimit],
				confirmationTime: [3, Math.max(3, this.applicationDeadline - 3)], // 成团确认日期：3到(渠道申请截止天数-3)
				maxPeople: [CONSTANTS.MIN_PEOPLE, this.maxPeopleLimit],
				minPeople: [this.minPeopleLimit, CONSTANTS.MAX_GROUP_PEOPLE],
				groupCount: [1, this.groupCountLimit], // 每期服务承载最大团数：1-20团
				groupMaxPeople: [6, 20], // 每小组名额上限：6-20人
				groupMinPeople: [5, 8], // 每小组名额下限：5-8人
				maxGroupsPerService: [1, this.maxGroupsPerServiceLimit] // 每期服务承载最大团数：1-20团（三类商家调用模式下受限制）
			}

			const [min, max] = limits[field] || [0, 999]
			const value = parseInt(this[field])

			if (isNaN(value) || value < min || value > max) {
				this[field] = Math.max(min, Math.min(max, value || min))
				this.showError(`请输入${min}-${max}之间的数值`)
			}

			// 当 applicationDeadline 改变时，检查并调整 confirmationTime
			if (field === 'applicationDeadline') {
				const maxConfirmationTime = Math.max(3, this.applicationDeadline - 3)
				if (this.confirmationTime > maxConfirmationTime) {
					this.confirmationTime = maxConfirmationTime
					this.showError(`成团确认日期必须至少小于渠道申请截止${3}天`)
				}
			}

			// 当 confirmationTime 改变时，确保它不超过 applicationDeadline - 3
			if (field === 'confirmationTime') {
				const maxConfirmationTime = Math.max(3, this.applicationDeadline - 3)
				if (this.confirmationTime > maxConfirmationTime) {
					this.confirmationTime = maxConfirmationTime
					this.showError(`成团确认日期必须至少小于渠道申请截止${3}天`)
				}
			}

			// 当 maxPeople（每团满员人数）改变时，确保它不能低于 minPeople（最低成团人数）
			if (field === 'maxPeople') {
				if (this.maxPeople < this.minPeople) {
					this.maxPeople = this.minPeople
					this.showError('每团满员人数不能低于最低成团人数')
				}
			}

			// 当 minPeople（最低成团人数）改变时，确保它不能高于 maxPeople（每团满员人数）
			if (field === 'minPeople') {
				if (this.minPeople > this.maxPeople) {
					this.minPeople = this.maxPeople
					this.showError('最低成团人数不能高于每团满员人数')
				}
			}
		},

		// 显示添加联系人表单
		showAddStaffForm() {
			this.showAddForm = true
			this.newStaff = {
				category: '',
				name: '',
				phone: ''
			}
		},

		// 显示工作人员配置弹窗
		showStaffPopup() {
			this.showStaffPopupForm = true
			this.contactTypeIndex = 0
			this.newStaff = {
				category: '',
				name: '',
				phone: ''
			}
		},

		// 关闭工作人员配置弹窗
		closeStaffPopup() {
			this.showStaffPopupForm = false
			this.contactTypeIndex = 0
			this.newStaff = {
				category: '',
				name: '',
				phone: ''
			}
		},


		// 处理联系人类型选择
		handleContactTypeChange(e) {
			const index = e.detail.value
			this.contactTypeIndex = index
			const selectedOption = this.contactTypeOptions[index]

			// 如果选择了"自定义"，弹出输入框让用户输入
			if (selectedOption.value === 'custom') {
				uni.showModal({
					title: '自定义类型',
					editable: true,
					placeholderText: '请输入联系人类型',
					success: (res) => {
						if (res.confirm && res.content && res.content.trim()) {
							this.newStaff.category = res.content.trim()
						} else {
							// 用户取消或未输入，重置为默认选项
							this.contactTypeIndex = 0
							this.newStaff.category = ''
						}
					},
					fail: () => {
						// 输入失败，重置为默认选项
						this.contactTypeIndex = 0
						this.newStaff.category = ''
					}
				})
			} else {
				this.newStaff.category = selectedOption.value
			}
		},

		// 取消添加联系人
		cancelAddStaff() {
			this.closeStaffPopup()
		},

		// 省市区选择器变化
		onRegionChange(e) {
			const [province, city, district] = e.detail.value
			this.gatherProvince = province || ''
			this.gatherCity = city || ''
			this.gatherDistrict = district || ''
			this.regionValue = [province, city, district]
			// 省市区选择器的值保存为 saleArea（接送区域）
			this.saleArea = `${this.gatherProvince}${this.gatherCity}${this.gatherDistrict}`
		},

		// 选择集散地址（地图选择）
		selectGatherAddress() {
			uni.chooseLocation({
				success: (res) => {
					if (res.address || res.name) {
						const selectedAddress = `${res.address || ''}${res.name ? '-' + res.name : ''}`
						this.gatherAreaDisplay = selectedAddress.trim()
						// 同时更新gatherArea作为数据传递
						this.gatherArea = selectedAddress.trim()
					}
				},
				fail: () => {
					this.showError('获取位置失败')
				}
			})
		},

		// 获取地址名称（显示在第二行）
		getAddressName(address) {
			if (!address) return ''
			if (address.includes('-')) {
				const parts = address.split('-')
				return parts[1] ? parts[1].trim() : ''
			}
			return ''
		},

		// 获取地址位置（显示在第一行）
		getAddressLocation(address) {
			if (!address) return ''
			if (address.includes('-')) {
				const parts = address.split('-')
				return parts[0].trim()
			}
			return address
		},

		// 确认添加联系人
		confirmAddStaff() {
			// 验证输入
			if (!this.newStaff.name.trim()) {
				this.showError('请输入姓名')
				return
			}
			if (!this.newStaff.phone.trim()) {
				this.showError('请输入电话')
				return
			}

			// 验证手机号格式
			const phoneRegex = /^1[3-9]\d{9}$/
			if (!phoneRegex.test(this.newStaff.phone)) {
				this.showError('请输入正确的手机号')
				return
			}

			// 添加到列表（附带 productType）
			this.staffList.push({
				category: this.newStaff.category.trim(),
				name: this.newStaff.name.trim(),
				phone: this.newStaff.phone.trim(),
				productType: Number(this.productType) || undefined
			})

			// 重置表单
			this.closeStaffPopup()
			this.showSuccess('联系人添加成功')
		},

		// 删除工作人员
		deleteStaff(index) {
			if (this.staffList.length <= 1) {
				this.showError('至少需要保留一个工作人员')
				return
			}

			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个工作人员吗？',
				success: (res) => {
					if (res.confirm) {
						this.staffList.splice(index, 1)
					}
				}
			})
		},

		// 计算预估价格（防抖处理）- 一类商家使用
		calculateEstimatedPrice() {
			// 清除之前的定时器
			if (this.priceCalculateTimer) {
				clearTimeout(this.priceCalculateTimer)
			}

			// 设置新的定时器
			this.priceCalculateTimer = setTimeout(() => {
				if (this.price > 0) {
					// 将计算结果转换为数字，而不是字符串
					this.estimatedPrice = parseFloat((this.price * (1 - this.rate)).toFixed(2))
					console.log('计算预估结算到账金额:', {
						price: this.price,
						rate: this.rate,
						estimatedPrice: this.estimatedPrice
					})
				} else {
					this.estimatedPrice = 0
				}
			}, 300)
		},

		// 计算二类商家预估结算到账金额（非申请调用模式 - 创建班期使用）
		calculateType2EstimatedPrice() {
			// 清除之前的定时器
			if (this.priceCalculateTimer) {
				clearTimeout(this.priceCalculateTimer)
			}

			// 设置新的定时器
			this.priceCalculateTimer = setTimeout(() => {
				if (this.secondServicePrice > 0) {
					// 预估结算到账金额 = 组团合计售价 * (1 - 手续费率)
					this.estimatedGroupSettlement = parseFloat((this.secondServicePrice * (1 - this.rate)).toFixed(2))
					console.log('计算二类商家预估结算到账金额:', {
						secondServicePrice: this.secondServicePrice,
						rate: this.rate,
						estimatedGroupSettlement: this.estimatedGroupSettlement
					})
				} else {
					this.estimatedGroupSettlement = 0
				}
			}, 300)
		},

		// 计算二类商家价格
		calculateType2Prices() {
			console.log('💰 计算二类商家价格')

			if (this.isApplyCall && this.businessType === 2) {
				// 🔵 B2申请调用模式（创建组团业务productType=4）
				// 输入：secondAddedServicePrice（组团增值服务售价）
				// 自动展示：price（目的地接待售价/泛营地接待售价）

				// 预估增值结算金额 = 组团增值服务售价 * (1 - 手续费率)
				if (this.groupAddedServicePrice > 0) {
					this.estimatedGroupSettlement = parseFloat((this.groupAddedServicePrice * (1 - this.rate)).toFixed(2))
				} else {
					this.estimatedGroupSettlement = 0
				}

				// B2合计售价 = 目的地接待服务售价 + 组团增值服务售价
				const destinationPrice = parseFloat(this.destinationServicePrice) || 0
				const groupAddedPrice = parseFloat(this.groupAddedServicePrice) || 0
				this.totalPrice = parseFloat((destinationPrice + groupAddedPrice).toFixed(2))

				console.log('✅ B2申请调用价格计算结果:', {
					destinationServicePrice: this.destinationServicePrice,
					groupAddedServicePrice: this.groupAddedServicePrice,
					estimatedGroupSettlement: this.estimatedGroupSettlement,
					totalPrice: this.totalPrice,
					rate: this.rate
				})
			} else {
				// 🔵 B2创建综合研学业务（productType=2）
				// 输入：secondServicePrice（服务售价-渠道）

				// 预估结算到账金额 = 服务售价 * (1 - 手续费率)
				if (this.secondServicePrice > 0) {
					this.secondEstimatedPrice = parseFloat((this.secondServicePrice * (1 - this.rate)).toFixed(2))
				} else {
					this.secondEstimatedPrice = 0
				}

				// estimatedPrice 用于显示
				this.estimatedPrice = this.secondEstimatedPrice

				// B2合计售价 = 服务售价（不展示，但要存数据库）
				this.secondTotalPrice = parseFloat(this.secondServicePrice) || 0

				console.log('✅ B2创建综合研学业务价格计算结果:', {
					secondServicePrice: this.secondServicePrice,
					secondEstimatedPrice: this.secondEstimatedPrice,
					secondTotalPrice: this.secondTotalPrice,
					rate: this.rate
				})
			}
		},

		// 计算三类商家价格
		calculateType3Prices() {
			console.log('💰 计算三类商家价格')

			// 🔵 B3申请调用B2的组团业务（创建研学活动productType=5）
			// 自动展示：thirdServicePrice（上游及组团服务API渠道售价 = B2的secondTotalPrice）
			// 输入：thirdAddedServicePrice（随团增值服务售价）

			// 预估增值结算金额 = 随团增值服务售价 * (1 - 手续费率)
			if (this.escortAServicePrice > 0) {
				this.escortASettlement = parseFloat((this.escortAServicePrice * (1 - this.rate)).toFixed(2))
			} else {
				this.escortASettlement = 0
			}

			// 合单售价 = 上游及组团服务API渠道售价 + 随团增值服务售价
			const upstream = parseFloat(this.upstreamApiPrice) || 0
			const escortA = parseFloat(this.escortAServicePrice) || 0
			this.totalPrice = parseFloat((upstream + escortA).toFixed(2))

			console.log('✅ B3申请调用价格计算结果:', {
				upstreamApiPrice: this.upstreamApiPrice,
				escortAServicePrice: this.escortAServicePrice,
				escortASettlement: this.escortASettlement,
				totalPrice: this.totalPrice,
				rate: this.rate
			})
		},

		// 验证价格
		validatePrice() {
			console.log('this.price', this.price)
			// 如果 price 为空字符串或无效，直接返回，不做处理
			if (!this.price || this.price === '') {
				return
			}

			const price = parseFloat(this.price)
			console.log('price', price)
			if (isNaN(price) || price < 0) {
				this.price = ''
				this.estimatedPrice = 0
				this.showError('请输入有效的价格')
			}

			// 验证二类商家的服务售价
			if (this.businessType === 2 && this.secondServicePrice !== undefined && this.secondServicePrice !== '') {
				const secondPrice = parseFloat(this.secondServicePrice)
				if (isNaN(secondPrice) || secondPrice < 0) {
					this.secondServicePrice = ''
					this.secondEstimatedPrice = 0
					this.estimatedPrice = 0
					this.showError('请输入有效的价格')
				}
			}
		},

		// 协议确认
		toggleAgreement() {
			this.agreementChecked = !this.agreementChecked
		},

		// 显示价格说明模态框
		showPriceModal(content) {
			uni.showModal({
				title: '说明',
				content: content || `扣收软件技术服务费（费率${this.rate * 100}%）后的实际到账金额`,
				showCancel: false
			})
		},

		// 通过key显示价格说明
		showPriceModalByKey(key) {
			const content = this.priceDescriptions[key] || ''
			// 替换动态内容
			const finalContent = content.replace('{{ rate * 100 }}', (this.rate * 100).toString())
			this.showPriceModal(finalContent)
		},

		// 显示协议
		showAgreement(title) {
			uni.showModal({
				title: title,
				content: '请仔细阅读相关协议条款...',
				showCancel: false
			})
		},

		// 验证所有字段
		validateAllFields() {
			// 根据商家类型和模式确定需要验证的价格字段
			let hasPrice = false
			if (!this.isApplyCall && (this.businessType === 1 || this.productType === '3')) {
				// 一类商家创建班期 或 B2创建目的地接待（productType=3）
				hasPrice = this.price > 0
			} else if (!this.isApplyCall && this.businessType === 2 && this.productType !== '3') {
				// 二类商家创建班期（排除目的地接待）
				hasPrice = this.secondServicePrice > 0
			} else if (this.isApplyCall && this.businessType === 2) {
				// 二类商家申请调用
				hasPrice = this.groupAddedServicePrice > 0
			} else if (this.isApplyCall && this.businessType === 3) {
				// 三类商家申请调用
				hasPrice = this.escortAServicePrice > 0
			} else if (this.isApplyCall && this.businessType === 1) {
				// 一类商家申请调用
				hasPrice = this.price > 0
			}

			console.log('🔍 validateAllFields 验证结果:', {
				selectedDates: this.selectedDates && this.selectedDates.length > 0,
				hasPrice: hasPrice,
				price: this.price,
				totalPrice: this.totalPrice,
				groupAddedServicePrice: this.groupAddedServicePrice,
				escortAServicePrice: this.escortAServicePrice,
				staffList: this.staffList.length,
				applicationDeadline: this.applicationDeadline,
				maxPeople: this.maxPeople,
				minPeople: this.minPeople,
				businessType: this.businessType,
				isApplyCall: this.isApplyCall
			})

			const baseValidation = this.selectedDates && this.selectedDates.length > 0 &&
				hasPrice &&
				this.staffList.length > 0

			// 根据商家类型验证不同的字段
			if (!this.isApplyCall && (this.businessType === 1 || this.productType === '3')) {
				// 一类商家创建班期 或 B2创建目的地接待（productType=3）
				return baseValidation &&
					this.applicationDeadline >= CONSTANTS.MIN_APPLICATION_DEADLINE &&
					this.maxPeople >= CONSTANTS.MIN_PEOPLE &&
					this.minPeople >= CONSTANTS.MIN_GROUP_PEOPLE
			} else if (!this.isApplyCall && this.businessType === 2 && this.productType !== '3') {
				// 二类商家创建班期（排除目的地接待）
				return baseValidation &&
					this.applicationDeadline >= CONSTANTS.MIN_APPLICATION_DEADLINE &&
					this.maxPeople >= CONSTANTS.MIN_PEOPLE &&
					this.minPeople >= CONSTANTS.MIN_GROUP_PEOPLE
			} else if (this.isApplyCall && this.businessType === 2) {
				// 二类商家申请调用：需要验证二类相关字段
				return baseValidation &&
					this.applicationDeadline >= CONSTANTS.MIN_APPLICATION_DEADLINE &&
					this.confirmationTime >= 3 &&
					this.maxPeople >= CONSTANTS.MIN_PEOPLE &&
					this.minPeople >= CONSTANTS.MIN_GROUP_PEOPLE &&
					this.groupMaxPeople > 0 &&
					this.groupMinPeople > 0 &&
					this.groupAddedServicePrice > 0
			} else if (this.isApplyCall && this.businessType === 3) {
				// 三类商家申请调用：需要验证三类相关字段
				return baseValidation &&
					this.applicationDeadline >= CONSTANTS.MIN_APPLICATION_DEADLINE &&
					this.groupMaxPeople > 0 &&
					this.groupMinPeople > 0 &&
					this.escortAServicePrice > 0
			}

			return baseValidation
		},

		// 区分班期数据：哪些需要更新，哪些需要创建
		categorizePeriodsForSave(allPeriodData) {
			const toUpdate = []
			const toCreate = []

			for (const periodItem of allPeriodData) {
				const periodSku = periodItem.periodSku
				if (!periodSku || !periodSku.availableDate) {
					console.warn('班期数据缺少必要字段，跳过:', periodItem)
					continue
				}

				// 根据日期查找对应的班期ID
				const { yearDate, monthDate, dayDate } = periodSku.availableDate
				const dateStr = `${yearDate}-${monthDate.padStart(2, '0')}-${dayDate.padStart(2, '0')}`
				const periodId = this.periodIdMap.get(dateStr)

				if (periodId) {
					// 该日期已有班期，需要更新
					toUpdate.push({
						periodId: periodId,
						data: periodItem
					})
				} else {
					// 新增的日期，需要创建
					toCreate.push(periodItem)
				}
			}

			return { toUpdate, toCreate }
		},

		// 显示错误信息
		showError(message) {
			uni.showToast({
				title: message,
				icon: 'none',
				duration: 2000
			})
		},

		// 显示成功信息
		showSuccess(message) {
			uni.showToast({
				title: message,
				icon: 'success',
				duration: 2000
			})
		},

		// 存草稿
		async saveDraft() {

			// 验证是否选择了日期（非申请调用模式且非编辑模式）
			if (!this.isApplyCall && !this.isEditPeriod && (!this.selectedDates || this.selectedDates.length === 0)) {
				this.showError('请先选择班期日期')
				return
			}

			// 申请调用模式：验证是否选择了班期
			if (this.isApplyCall && (!this.selectedDates || !this.selectedDates.some(item => item.isSelected))) {
				this.showError('请选择要申请的班期')
				return
			}

			try {
				const allPeriodData = this.preparePeriodData(false)
				console.log('准备的草稿数据:', JSON.stringify(allPeriodData, null, 2))

				// 申请调用模式：需要先创建产品（status=0）
				if (this.isApplyCall) {
					console.log('📌 申请调用模式：先创建产品草稿')

					// 多班期：为每个选中的日期分别提交申请草稿
					const selectedList = (this.selectedDates || []).filter(i => i.isSelected)
					if (selectedList.length === 0) {
						throw new Error('请选择要申请的班期')
					}

					// 构造表单数组
					const forms = selectedList.map(sel => {
						const applyData = this.prepareApplyData(sel)
						const periodDataPer = this.preparePeriodData(false, sel)
						applyData.periodSku = periodDataPer[0].periodSku
						applyData.periodSku.status = 0
						applyData.status = 8
						return applyData
					})
					if (forms.length > 1) {
						await this.applyPeriodBatch(forms)
					} else {
						await this.applyPeriod(forms[0])
					}
					this.showSuccess(`申请草稿已保存（${forms.length} 个班期）`)

					// 延迟跳转，让用户看到成功提示
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/merchant/index/index'
						})
					}, 1500)
					return
				}

				if (this.isEditPeriod) {
					// 编辑模式：区分更新和新增
					const { toUpdate, toCreate } = this.categorizePeriodsForSave(allPeriodData)

					console.log(`📝 编辑模式 - 更新 ${toUpdate.length} 个班期，新增 ${toCreate.length} 个班期`)

					// 批量更新已存在的班期
					for (const { periodId, data } of toUpdate) {
						await this.updatePeriod(periodId, data)
					}

					// 批量创建新增的班期
					if (toCreate.length > 0) {
						await this.createPeriod(toCreate)
					}

					this.showSuccess(`班期草稿已保存（更新${toUpdate.length}个，新增${toCreate.length}个）`)
				} else {
					// 创建模式：全部新建
					const res = await this.createPeriod(allPeriodData)
					console.log('✅ 班期草稿创建成功:', res)
					this.showSuccess('班期草稿已保存')
				}

				// 注意：不更新产品状态，产品保持原状态（通常是0-草稿箱）

				// 延迟后返回上一页
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					})
				}, 1500)
			} catch (error) {
				console.error('❌ 保存草稿失败:', error)
				this.showError(error.message || '保存草稿失败')
			}
		},

		// 申请班期（旅行社/教培专用）- 调用后端的申请接口
		async applyPeriod(applyData) {
			try {
				console.log('🚀 调用申请接口，参数:', applyData)
				const res = await request({
					url: '/call-apply/apply',
					method: 'POST',
					data: applyData,
					loading: true
				})

				console.log('✅ 申请接口返回:', res)
				if (res.code === 200) {
					return res.data
				} else {
					throw new Error(res.message || res.msg || '申请提交失败')
				}
			} catch (error) {
				console.error('❌ 申请提交失败:', error)
				throw error
			}
		},

		// 批量申请班期：一次创建一个产品 + 多个班期
		async applyPeriodBatch(applyForms) {
			try {
				console.log('🚀 调用批量申请接口，参数:', applyForms)
				const res = await request({
					url: '/call-apply/apply-batch',
					method: 'POST',
					data: applyForms,
					loading: true
				})
				console.log('✅ 批量申请接口返回:', res)
				if (res.code === 200) {
					return res.data
				} else {
					throw new Error(res.message || res.msg || '批量申请提交失败')
				}
			} catch (error) {
				console.error('❌ 批量申请提交失败:', error)
				throw error
			}
		},

		// 更新产品状态
		async updateProductStatus(spuId, status) {
			try {
				console.log('🚀 更新产品状态，参数:', { spuId, status })
				const res = await request({
					url: `/product-spu/updateStatus?spuId=${spuId}&status=${status}`,
					method: 'POST',
					loading: false
				})

				console.log('✅ 更新产品状态返回:', res)
				if (res.code === 200) {
					return res.data
				} else {
					throw new Error(res.message || res.msg || '更新产品状态失败')
				}
			} catch (error) {
				console.error('❌ 更新产品状态失败:', error)
				throw error
			}
		},

		// 准备申请数据（申请调用模式专用）
		prepareApplyData(selectedPeriodParam = null) {
			const companyInfo = uni.getStorageSync('companyInfo') || {}
			console.log('=== 开始准备申请调用数据 ===')
			console.log('this.sourcePeriodId:', this.sourcePeriodId)
			console.log('this.sourceSkuId:', this.sourceSkuId)
			console.log('this.productId:', this.productId)
			console.log('this.sourceMerchantId:', this.sourceMerchantId)
			console.log('this.editedProductData:', this.editedProductData)

			// 获取选中的班期信息
			const selectedPeriod = selectedPeriodParam || (this.selectedDates && this.selectedDates.find(item => item.isSelected))
			if (!selectedPeriod) {
				throw new Error('请选择班期')
			}

			console.log('✅ 用户选中的班期:', selectedPeriod)

			// 使用用户在页面上选中的班期ID（这是真实的班期ID）
			const sourcePeriodId = selectedPeriod.periodId

			// 从产品信息中获取SKU ID
			const sourceSkuId = this.sourceSkuId || this.productInfo?.mainInfo?.productSku?.id || this.skuId

			// 获取源商家ID（从availablePeriods中获取）
			const sourceMerchantId = this.availablePeriods.length > 0
				? this.availablePeriods[0].merchantId
				: this.sourceMerchantId

			console.log('✅ 源班期ID:', sourcePeriodId)
			console.log('✅ 源SKU ID:', sourceSkuId)
			console.log('✅ 源商家ID:', sourceMerchantId)

			const applyData = {
				spuId: Number(this.productId), // 源SPU ID
				skuId: sourceSkuId ? Number(sourceSkuId) : undefined, // 源SKU ID
				periodId: sourcePeriodId ? Number(sourcePeriodId) : undefined, // 源班期ID（用户选中的班期）
				sourceMerchantId: sourceMerchantId ? Number(sourceMerchantId) : undefined, // 源商家ID
				sourceMerchantType: 1, // 源商家类型（一类商家）
				targetMerchantId: Number(companyInfo.id), // 目标商家ID（当前商家）
				targetMerchantType: Number(companyInfo.businessType), // 目标商家类型
				isAllowRecursive: 0, // 不允许递归调用
				applyReason: '申请合作',
				salePrice: String(this.price), // 销售价格
				saleArea: this.saleArea || '', // 销售区域
				status: -1,
				sourceProductType: this.productType
			}

			// 如果有编辑后的产品数据，添加到申请数据中
			if (this.editedProductData) {
				console.log('✅ 使用编辑后的产品数据')
				applyData.editedSku = this.editedProductData.productSku
				applyData.editedSpuName = this.editedProductData.productSpu.name
				applyData.editedMainImage = this.editedProductData.productSpu.mainImage
			}

			console.log('✅ 申请调用数据准备完成:', applyData)

			return applyData
		},

		// 提交上架
		async submitPeriod() {
			if (!this.canSubmit) {
				this.showError('请完善所有必要信息')
				return
			}

			// 验证是否选择了日期（非申请调用且非编辑模式）
			if (!this.isApplyCall && !this.isEditPeriod && (!this.selectedDates || this.selectedDates.length === 0)) {
				this.showError('请先选择班期日期')
				return
			}

			// 验证是否选择了班期（申请调用模式）
			if (this.isApplyCall && (!this.selectedDates || !this.selectedDates.some(item => item.isSelected))) {
				this.showError('请选择要申请的班期')
				return
			}

			try {
				const companyInfo = uni.getStorageSync('companyInfo') || {}

				// 如果是申请调用模式
				if (this.isApplyCall) {
					console.log('📌 申请调用模式，调用申请接口')

					// 多班期：逐个提交
					const selectedList = (this.selectedDates || []).filter(i => i.isSelected)
					if (selectedList.length === 0) {
						throw new Error('请选择要申请的班期')
					}
					const forms = selectedList.map(sel => {
						const periodData = this.preparePeriodData(true, sel)
						const applyData = this.prepareApplyData(sel)
						applyData.periodSku = periodData[0].periodSku
						return applyData
					})
					if (forms.length > 1) {
						await this.applyPeriodBatch(forms)
					} else {
						await this.applyPeriod(forms[0])
					}
					this.showSuccess(`申请提交成功（${forms.length} 个班期）`)

					// 延迟跳转，让用户看到成功提示
					setTimeout(() => {
						uni.navigateBack({
							delta: 2 // 返回两层，回到产品列表
						})
					}, 1500)
					return
				}

				// 创建新产品模式：所有商家类型都只是创建或更新班期
				const allPeriodData = this.preparePeriodData(true)
				console.log('准备的班期数据:', JSON.stringify(allPeriodData, null, 2))

				if (this.isEditPeriod) {
					// 编辑模式：区分更新和新增
					const { toUpdate, toCreate } = this.categorizePeriodsForSave(allPeriodData)

					console.log(`📝 编辑模式 - 更新 ${toUpdate.length} 个班期，新增 ${toCreate.length} 个班期`)

					// 批量更新已存在的班期
					for (const { periodId, data } of toUpdate) {
						await this.updatePeriod(periodId, data)
					}

					// 批量创建新增的班期
					if (toCreate.length > 0) {
						await this.createPeriod(toCreate)
					}

					console.log('✅ 班期更新成功')

					// 更新产品状态为 1-待上架(待平台审核)
					await this.updateProductStatus(this.productId, 1)
					console.log('✅ 产品状态已更新为待上架')

					this.showSuccess('班期上架成功')
				} else {
					// 创建模式：全部新建
					console.log('✅ 创建新班期模式')
					console.log('班期数据数量:', allPeriodData.length)

					// 1. 创建班期
					const res = await this.createPeriod(allPeriodData)
					console.log('✅ 创建班期响应:', res)
					this.periodId = res.data;

					// 2. 更新产品状态为 1-待上架(待平台审核)
					await this.updateProductStatus(this.productId, 1)
					console.log('✅ 产品状态已更新为待上架')

					this.showSuccess('班期上架成功')
				}

				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/merchant/index/index'
					})
				}, 1500)

			} catch (error) {
				console.error('❌ 提交失败:', error)
				this.showError(error.message || '提交失败')
			}
		},

		// 准备班期数据
		preparePeriodData(isSubmit = false, selectedPeriodParam = null) {
			// 准备联系人数据和随队人员数据
			let contactPersons = []
			let teamMembers = null

			if (this.isApplyCall && this.businessType === 3) {
				// 三类商家申请调用：
				// contact 保存源商家（二类商家）的联系人
				contactPersons = (this.sourceContactList || []).map(contact => ({
					category: contact.category || '',
					name: contact.name || '',
					phone: contact.phone || '',
					businessType: contact.businessType || this.sourceMerchantType,
					productType: contact.productType !== undefined && contact.productType !== null
						? Number(contact.productType)
						: (Number(this.productType) || undefined)
				}))
				// teamMembers 保存三类商家的随队人员
				teamMembers = this.staffList.map(staff => ({
					category: staff.category || '',
					name: staff.name || '',
					phone: staff.phone || '',
					businessType: 3,
					productType: staff.productType !== undefined && staff.productType !== null
						? Number(staff.productType)
						: (Number(this.productType) || undefined)
				}))
			} else {
				// 其他情况：contact 保存工作人员/联系人
				contactPersons = this.staffList.map(staff => ({
					category: staff.category || '',
					name: staff.name || '',
					phone: staff.phone || '',
					productType: staff.productType !== undefined && staff.productType !== null
						? Number(staff.productType)
						: (Number(this.productType) || undefined)
				}))
			}

			let { gatherProvince, gatherCity, gatherDistrict, gatherArea } = this;
			console.log('gatherProvince,gatherCity,gatherDistrict,gatherArea', gatherProvince, gatherCity, gatherDistrict, gatherArea)
			// 获取当前选中的班期（申请调用模式）
			let selectedPeriodDate = null
			if (this.isApplyCall) {
				const selectedPeriod = selectedPeriodParam || (this.selectedDates && this.selectedDates.find(item => item.isSelected))
				if (selectedPeriod) {
					// 使用选中班期的日期信息
					const dateParts = selectedPeriod.DateName.split('-')
					selectedPeriodDate = {
						yearDate: dateParts[0],
						monthDate: dateParts[1],
						dayDate: dateParts[2],
						weekDate: selectedPeriod.WeekName
					}
				}
			}

			// 准备班期数据
			let periodData = []

			if (this.isApplyCall) {
				// 申请调用模式：基于选中班期的日期创建班期数据
				const selectedPeriod = selectedPeriodParam || (this.selectedDates && this.selectedDates.find(item => item.isSelected))
				if (!selectedPeriod || !selectedPeriodDate) {
					throw new Error('请选择班期')
				}

				const companyInfo = uni.getStorageSync('companyInfo') || { id: 1 }

				// 根据业务类型设置 confirmationTime
				// 申请调用模式：二类商家和三类商家都需要设置 confirmationTime
				let confirmationTimeValue = 0
				if (this.businessType === 2) {
					// 二类商家申请调用：使用用户输入的 confirmationTime
					confirmationTimeValue = parseInt(this.confirmationTime) || 0
					console.log('✅ 二类商家申请调用 - confirmationTime:', confirmationTimeValue)
				} else if (this.businessType === 3) {
					// 三类商家申请调用：使用从上游班期获取的 confirmationTime（已在选择班期时加载）
					confirmationTimeValue = parseInt(this.confirmationTime) || 0
					console.log('✅ 三类商家申请调用 - confirmationTime:', confirmationTimeValue)
				}

				// 三类商家申请调用时，从选中的班期获取 saleArea
				let saleAreaValue = this.saleArea || ''
				if (this.businessType === 3 && this.isApplyCall) {
					// 从 availablePeriods 中获取选中班期的 saleArea
					const sourcePeriod = this.availablePeriods.find(p => p.id === selectedPeriod.periodId)
					if (sourcePeriod && sourcePeriod.saleArea) {
						saleAreaValue = sourcePeriod.saleArea
						console.log('✅ 三类商家申请调用 - 从上游班期获取 saleArea:', saleAreaValue)
					} else {
						console.warn('⚠️ 未找到上游班期的 saleArea，periodId:', selectedPeriod.periodId)
					}
				}

				const periodSkuData = {
					spuId: this.productId,
					merchantId: companyInfo.id,
					availableDate: selectedPeriodDate,
					applicationDeadline: parseInt(this.applicationDeadline),
					confirmationTime: confirmationTimeValue,
					fullNumberOfPeople: parseInt(this.maxPeople),
					leastNumberOfPeople: parseInt(this.minPeople),
					fullNumberOfRegiment: parseInt(this.groupCount) || 0,
					contact: contactPersons,
					status: isSubmit ? 1 : 0,
					inventory: parseInt(this.maxPeople),
					saleArea: saleAreaValue, // 省市区选择器的值（三类商家从上游班期获取）
					saleMode: this.salesModeOptions[this.salesModeIndex] || 'API渠道协作',
					gatherArea: this.gatherArea || '', // 地图地址选择器的值
					rate: parseFloat(this.rate) || 0.06,
				}

				// 三类商家申请调用时，设置 teamMembers
				if (this.isApplyCall && this.businessType === 3 && teamMembers && teamMembers.length > 0) {
					periodSkuData.teamMembers = teamMembers
				}

				periodData = [{
					periodSku: periodSkuData
				}]
			} else {
				// 创建新产品模式：使用 periodList
				// 根据业务类型设置 confirmationTime
				// 模板显示条件：
				// 1. productType === '1' || productType === '3'：显示"成团确认入日期"（一类商家创建泛营地接待 或 二类商家创建目的地接待）
				// 2. businessType === 2 && productType !== '3'：显示"成团确认日期"（二类商家创建综合研学业务）
				let confirmationTimeValue = 0
				if ((this.businessType === 1 && this.productType === '1') ||
					(this.businessType === 2)) {
					// 一类商家创建泛营地接待（productType=1）或 二类商家创建任何产品：使用用户输入的 confirmationTime
					confirmationTimeValue = parseInt(this.confirmationTime) || 0
				}

				periodData = this.periodList.map(period => {
					const periodSku = {
						...period.periodSku,
						applicationDeadline: parseInt(this.applicationDeadline),
						confirmationTime: confirmationTimeValue,
						fullNumberOfPeople: parseInt(this.maxPeople),
						leastNumberOfPeople: parseInt(this.minPeople),
						fullNumberOfRegiment: parseInt(this.groupCount) || 0,
						contact: contactPersons,
						status: isSubmit ? 1 : 0,
						inventory: parseInt(this.maxPeople),
						saleArea: this.saleArea || '', // 省市区选择器的值
						saleMode: this.salesModeOptions[this.salesModeIndex] || 'API渠道协作',
						gatherArea: this.gatherArea || '', // 地图地址选择器的值（三类商家使用）
						rate: parseFloat(this.rate) || 0.06,
					}

					return { periodSku }
				})
			}

			// 处理价格字段
			const processedPeriodData = periodData.map(({ periodSku }) => {

				console.log('📊 准备班期价格数据 - 当前模式:', {
					businessType: this.businessType,
					productType: this.productType,
					isApplyCall: this.isApplyCall
				})

				// 🔑 根据业务场景存储对应的价格字段

				// 场景1: B1创建泛营地接待(productType=1)
				if (!this.isApplyCall && this.businessType === 1) {
					periodSku.price = parseFloat(this.price) || 0
					periodSku.estimatedPrice = parseFloat(this.estimatedPrice) || parseFloat((periodSku.price * (1 - this.rate)).toFixed(2))

					console.log('✅ B1创建泛营地接待价格:', {
						price: periodSku.price,
						estimatedPrice: periodSku.estimatedPrice
					})
				}

				// 场景2: B2创建综合研学业务(productType=2)
				else if (!this.isApplyCall && this.businessType === 2 && this.productType === '2') {
					periodSku.secondServicePrice = parseFloat(this.secondServicePrice) || 0
					periodSku.secondEstimatedPrice = parseFloat(this.secondEstimatedPrice) || parseFloat((periodSku.secondServicePrice * (1 - this.rate)).toFixed(2))
					periodSku.secondTotalPrice = parseFloat(this.secondTotalPrice) || periodSku.secondServicePrice

					// 小组设置字段
					periodSku.groupMaxPeople = parseInt(this.groupMaxPeople) || 0
					periodSku.groupMinPeople = parseInt(this.groupMinPeople) || 0

					console.log('✅ B2创建综合研学业务价格:', {
						secondServicePrice: periodSku.secondServicePrice,
						secondEstimatedPrice: periodSku.secondEstimatedPrice,
						secondTotalPrice: periodSku.secondTotalPrice,
						groupMaxPeople: periodSku.groupMaxPeople,
						groupMinPeople: periodSku.groupMinPeople
					})
				}

				// 场景3: B2创建目的地接待(productType=3)
				else if (!this.isApplyCall && this.businessType === 2 && this.productType === '3') {
					periodSku.price = parseFloat(this.price) || 0
					periodSku.estimatedPrice = parseFloat(this.estimatedPrice) || parseFloat((periodSku.price * (1 - this.rate)).toFixed(2))

					console.log('✅ B2创建目的地接待价格:', {
						price: periodSku.price,
						estimatedPrice: periodSku.estimatedPrice
					})
				}

				// 场景4: B2调用B1的泛营地接待(productType=1) 或 B2的目的地接待(productType=3) -> 创建组团业务(productType=4)
				else if (this.isApplyCall && this.businessType === 2) {
					periodSku.secondServicePrice = parseFloat(this.destinationServicePrice) || 0  // 目的地接待售价(自动展示的price)
					periodSku.secondAddedServicePrice = parseFloat(this.groupAddedServicePrice) || 0  // 组团增值服务售价(用户输入)
					periodSku.secondEstimatedPrice = parseFloat(this.estimatedGroupSettlement) || parseFloat((periodSku.secondAddedServicePrice * (1 - this.rate)).toFixed(2))  // 预估增值结算金额
					periodSku.secondTotalPrice = parseFloat(this.totalPrice) || parseFloat((periodSku.secondServicePrice + periodSku.secondAddedServicePrice).toFixed(2))  // B2合计售价

					// 小组设置字段
					periodSku.groupMaxPeople = parseInt(this.groupMaxPeople) || 0
					periodSku.groupMinPeople = parseInt(this.groupMinPeople) || 0

					console.log('✅ B2申请调用创建组团业务价格:', {
						secondServicePrice: periodSku.secondServicePrice,
						secondAddedServicePrice: periodSku.secondAddedServicePrice,
						secondEstimatedPrice: periodSku.secondEstimatedPrice,
						secondTotalPrice: periodSku.secondTotalPrice
					})
				}

				// 场景5: B3调用B2的组团业务(productType=4) -> 创建研学活动(productType=5)
				else if (this.isApplyCall && this.businessType === 3) {
					periodSku.thirdServicePrice = parseFloat(this.upstreamApiPrice) || 0  // 上游及组团服务API渠道售价(B2的secondTotalPrice)
					periodSku.thirdAddedServicePrice = parseFloat(this.escortAServicePrice) || 0  // 随团增值服务售价(用户输入)
					periodSku.thirdEstimatedPrice = parseFloat(this.escortASettlement) || parseFloat((periodSku.thirdAddedServicePrice * (1 - this.rate)).toFixed(2))  // 预估增值结算金额
					periodSku.totalPrice = parseFloat(this.totalPrice) || parseFloat((periodSku.thirdServicePrice + periodSku.thirdAddedServicePrice).toFixed(2))  // 合单售价

					// 小组设置字段
					periodSku.groupMaxPeople = parseInt(this.groupMaxPeople) || 0
					periodSku.groupMinPeople = parseInt(this.groupMinPeople) || 0
					periodSku.maxGroupsPerService = parseInt(this.maxGroupsPerService) || 0

					console.log('✅ B3申请调用创建研学活动价格:', {
						thirdServicePrice: periodSku.thirdServicePrice,
						thirdAddedServicePrice: periodSku.thirdAddedServicePrice,
						thirdEstimatedPrice: periodSku.thirdEstimatedPrice,
						totalPrice: periodSku.totalPrice
					})
				}

				return {
					periodSku
				}
			})

			console.log('✅ preparePeriodData 返回:', processedPeriodData)
			return processedPeriodData
		},

		// 显示加载状态
		showLoading(title = '处理中...') {
			uni.showLoading({
				title: title,
				mask: true
			})
		},

		// 隐藏加载状态
		hideLoading() {
			uni.hideLoading()
		},

		// 显示确认对话框
		showConfirm(title, content) {
			return new Promise((resolve) => {
				uni.showModal({
					title: title,
					content: content,
					success: (res) => {
						resolve(res.confirm)
					}
				})
			})
		},

		// 网络错误处理
		handleNetworkError(error) {
			console.error('网络错误:', error)

			if (error.code === 'NETWORK_ERROR') {
				this.showError('网络连接失败，请检查网络设置')
			} else if (error.code === 'TIMEOUT') {
				this.showError('请求超时，请稍后重试')
			} else {
				this.showError('操作失败，请稍后重试')
			}
		},

		// 表单验证
		validateForm() {
			const errors = []

			if (!this.selectedDates || this.selectedDates.length === 0) {
				errors.push('请选择班期日期')
			}

			if (this.price <= 0) {
				errors.push('请输入有效的服务价格')
			}


			if (this.applicationDeadline < CONSTANTS.MIN_APPLICATION_DEADLINE ||
				this.applicationDeadline > CONSTANTS.MAX_APPLICATION_DEADLINE) {
				errors.push(`申请截止天数应在${CONSTANTS.MIN_APPLICATION_DEADLINE}-${CONSTANTS.MAX_APPLICATION_DEADLINE}天之间`)
			}

			if (this.maxPeople < CONSTANTS.MIN_PEOPLE || this.maxPeople > CONSTANTS.MAX_PEOPLE) {
				errors.push(`人数上限应在${CONSTANTS.MIN_PEOPLE}-${CONSTANTS.MAX_PEOPLE}人之间`)
			}

			if (this.minPeople < CONSTANTS.MIN_GROUP_PEOPLE || this.minPeople > CONSTANTS.MAX_GROUP_PEOPLE) {
				errors.push(`人数下限应在${CONSTANTS.MIN_GROUP_PEOPLE}-${CONSTANTS.MAX_GROUP_PEOPLE}人之间`)
			}

			if (this.minPeople >= this.maxPeople) {
				errors.push('人数下限应小于人数上限')
			}

			return errors
		},

		// 数据持久化
		saveToLocalStorage() {
			const formData = {
				selectedDates: this.selectedDates,
				applicationDeadline: this.applicationDeadline,
				maxPeople: this.maxPeople,
				minPeople: this.minPeople,
				price: this.price,
				staffList: this.staffList,
				salesModeIndex: this.salesModeIndex,
				saleArea: this.saleArea,
				agreementChecked: this.agreementChecked,
				timestamp: Date.now()
			}

			try {
				uni.setStorageSync('periodCreateDraft', JSON.stringify(formData))
			} catch (error) {
				console.error('保存草稿失败:', error)
			}
		},

		// 从本地存储恢复数据
		loadFromLocalStorage() {
			try {
				const draftData = uni.getStorageSync('periodCreateDraft')
				if (draftData) {
					const data = JSON.parse(draftData)
					// 检查数据是否过期（24小时）
					if (Date.now() - data.timestamp < 24 * 60 * 60 * 1000) {
						this.applicationDeadline = data.applicationDeadline || 60
						this.maxPeople = data.maxPeople || 30
						this.minPeople = data.minPeople || 30
						this.price = data.price || 0
						this.staffList = data.staffList || []
						this.salesModeIndex = data.salesModeIndex || 0
						this.saleArea = data.saleArea || ''
						this.agreementChecked = data.agreementChecked || false

						if (data.selectedDates && data.selectedDates.length > 0) {
							this.selectedDates = data.selectedDates
							this.createPeriodList(data.selectedDates)
						}

						this.calculateEstimatedPrice()
					}
				}
			} catch (error) {
				console.error('加载草稿失败:', error)
			}
		},

		// 清除草稿数据
		clearDraft() {
			try {
				uni.removeStorageSync('periodCreateDraft')
			} catch (error) {
				console.error('清除草稿失败:', error)
			}
		},

		// 将班期数据转换为日期卡片格式
		convertPeriodsToDateCards() {
			// 确保 availablePeriods 是数组
			if (!this.availablePeriods || !Array.isArray(this.availablePeriods)) {
				console.warn('availablePeriods 不是有效数组:', this.availablePeriods)
				this.selectedDates = []
				return
			}

			this.selectedDates = this.availablePeriods.map((period, index) => {
				// 检查 availableDate 是否存在
				if (!period.availableDate) {
					console.warn('班期缺少日期信息:', period)
					return null
				}

				const { yearDate, monthDate, dayDate, weekDate } = period.availableDate
				const dateStr = `${yearDate}-${monthDate.padStart(2, '0')}-${dayDate.padStart(2, '0')}`

				// 🔍 根据申请调用场景确定应该显示的价格
				let displayPrice = 0
				if (this.isApplyCall) {
					// 申请调用模式：根据源商家类型确定价格字段
					if (this.sourceMerchantType === 1) {
						// B2调用B1：显示B1的 price（泛营地接待售价/渠道价）
						displayPrice = period.price || 0
						console.log('🔵 B2调用B1班期价格:', {
							periodId: period.id,
							price: period.price,
							displayPrice: displayPrice
						})
					} else if (this.sourceMerchantType === 2) {
						// B3调用B2：显示B2的 secondTotalPrice（B2合计售价）
						displayPrice = period.secondTotalPrice || 0
						console.log('🔵 B3调用B2班期价格:', {
							periodId: period.id,
							price: period.price,
							secondTotalPrice: period.secondTotalPrice,
							displayPrice: displayPrice
						})
					}
				} else {
					// 创建新产品模式：根据productType确定价格
					if (this.productType === '2') {
						// B2创建综合研学业务：显示 secondTotalPrice
						displayPrice = period.secondTotalPrice || 0
					} else {
						// B1创建泛营地接待 或 B2创建目的地接待：显示 price
						displayPrice = period.price || 0
					}
				}

				// 判断是否默认选中：申请调用模式下默认不选中任何班期，需要用户手动选择
				let isSelected = false
				if (this.isApplyCall) {
					// 申请调用模式：不默认勾选，需要用户手动选择
					isSelected = false
				} else {
					// 创建新产品模式：符合条件的默认勾选
					isSelected = this.isPeriodSelectableByDate(dateStr)
				}

				return {
					DateName: dateStr,
					WeekName: weekDate,
					periodId: period.id || `period_${index}`, // 如果period.id不存在，使用索引作为ID
					originalIndex: index, // 添加原始索引
					isSelected: isSelected,
					periodData: {
						price: displayPrice, // 使用计算后的显示价格
						leastNumberOfPeople: period.leastNumberOfPeople,
						fullNumberOfPeople: period.fullNumberOfPeople,
						inventory: period.inventory,
						saleArea: period.saleArea,
						applicationDeadline: period.applicationDeadline
					}
				}
			}).filter(item => item !== null) // 过滤掉无效的班期

			// 更新 selectedPeriodIds
			this.selectedPeriodIds = this.selectedDates.filter(item => item.isSelected).map(item => item.periodId)

			console.log('✅ 转换后的班期日期卡片:', this.selectedDates)
			console.log('✅ 默认选中的班期ID:', this.selectedPeriodIds)
		},

		// 判断班期是否可选（基于当前时间 + 渠道申请截止天数）- 接受日期字符串
		isPeriodSelectableByDate(dateStr) {
			if (!dateStr) {
				return false
			}

			// 获取当前时间
			const now = new Date()
			// 获取渠道申请截止天数，如果没有则使用默认值 60
			const deadlineDays = this.applicationDeadline || 60

			// 计算截止时间：当前时间 + 渠道申请截止天数
			const deadlineTime = new Date(now)
			deadlineTime.setDate(now.getDate() + deadlineDays)

			// 解析班期日期
			const periodDate = new Date(dateStr)
			// 设置时间为当天 0:0:0，只比较日期
			periodDate.setHours(0, 0, 0, 0)
			deadlineTime.setHours(0, 0, 0, 0)

			// 如果班期日期在截止时间之前（或等于），则不可选
			// 如果班期日期在截止时间之后，则可选
			return periodDate > deadlineTime
		},

		// 判断班期是否可选（基于当前时间 + 渠道申请截止天数）- 接受班期对象
		isPeriodSelectable(periodItem) {
			if (!periodItem.DateName) {
				return false
			}
			return this.isPeriodSelectableByDate(periodItem.DateName)
		},

		// 处理班期选择
		handlePeriodSelect(periodItem) {
			// A类日期选择：不允许取消选中
			if (this.isAClassDateSelection && periodItem.isSelected) {
				console.log('❌ A类日期选择不允许取消选中，请到全部班期页面操作')
				return
			}

			// 如果日期已选中，允许点击（即使 isPeriodSelectable 返回 false）
			// 这样可以允许用户取消选中已过期的日期
			if (!periodItem.isSelected) {
				// 只有未选中的日期才需要检查是否可选
				if (!this.isPeriodSelectable(periodItem)) {
					console.log('❌ 该班期已过期，不可选择')
					return
				}
			}

			// 使用多种方式查找匹配的班期
			let index = -1

			// 方法1：使用periodId匹配
			if (periodItem.periodId) {
				index = this.selectedDates.findIndex(item => item.periodId === periodItem.periodId)
			}

			// 方法2：使用原始索引匹配
			if (index === -1 && periodItem.originalIndex !== undefined) {
				index = this.selectedDates.findIndex(item => item.originalIndex === periodItem.originalIndex)
			}

			// 方法3：使用日期匹配
			if (index === -1) {
				index = this.selectedDates.findIndex(item => item.DateName === periodItem.DateName)
			}

			if (index !== -1) {
				// 切换选中状态
				const newSelectedState = !this.selectedDates[index].isSelected

				// 申请调用模式：允许多选，不再限制为单选

				// 直接修改属性
				this.selectedDates[index].isSelected = newSelectedState

				// 同步更新选中的班期ID列表
				if (newSelectedState) {
					if (!this.selectedPeriodIds.includes(periodItem.periodId)) {
						this.selectedPeriodIds.push(periodItem.periodId)
					}

					// 申请调用模式：自动填充班期价格到对应的价格字段
					if (this.isApplyCall && periodItem.periodData && periodItem.periodData.price) {
						const periodPrice = periodItem.periodData.price
						console.log('✅ 选中班期，自动填充价格:', periodPrice)

						if (this.businessType === 2) {
							// B2申请调用B1(productType=1) 或 B2(productType=3)
							// 自动填充：目的地接待服务售价 = 班期price
							this.destinationServicePrice = periodPrice
							console.log('🔵 B2申请调用 - 自动填充目的地接待服务售价:', this.destinationServicePrice)
							this.calculateType2Prices()
						} else if (this.businessType === 3) {
							// B3申请调用B2(productType=4)
							// 自动填充：上游及组团服务API渠道售价 = 班期price（实际是B2的secondTotalPrice）
							this.upstreamApiPrice = periodPrice
							console.log(' B3申请调用 - 自动填充上游及组团服务API渠道售价:', this.upstreamApiPrice)
							this.calculateType3Prices()
						}
					}

					// 申请调用模式（一类和二类商家）：保存初始名额设置值
					if (this.isApplyCall && (this.businessType === 1 || this.businessType === 2)) {
						const selectedPeriod = this.availablePeriods.find(p => p.id === periodItem.periodId)
						if (selectedPeriod) {
							// 保存初始值（只在第一次选择时保存）
							if (this.initialMaxPeople === null && selectedPeriod.fullNumberOfPeople) {
								this.initialMaxPeople = selectedPeriod.fullNumberOfPeople
								this.maxPeople = selectedPeriod.fullNumberOfPeople
							}
							if (this.initialMinPeople === null && selectedPeriod.leastNumberOfPeople) {
								this.initialMinPeople = selectedPeriod.leastNumberOfPeople
								this.minPeople = selectedPeriod.leastNumberOfPeople
							}
							if (this.initialGroupCount === null && selectedPeriod.fullNumberOfRegiment) {
								this.initialGroupCount = selectedPeriod.fullNumberOfRegiment
								this.groupCount = selectedPeriod.fullNumberOfRegiment
							}
							if (this.initialApplicationDeadline === null && selectedPeriod.applicationDeadline) {
								this.initialApplicationDeadline = selectedPeriod.applicationDeadline
								this.applicationDeadline = selectedPeriod.applicationDeadline
							}
							console.log('✅ 申请调用模式 - 保存初始名额设置:', {
								initialMaxPeople: this.initialMaxPeople,
								initialMinPeople: this.initialMinPeople,
								initialGroupCount: this.initialGroupCount,
								initialApplicationDeadline: this.initialApplicationDeadline
							})
						}
					}

					// 三类商家申请调用：加载选中班期的源商家联系人和成团确认时间，以及保存初始每期服务承载最大团数
					if (this.isApplyCall && this.businessType === 3) {
						this.loadSourceContactFromPeriod(periodItem.periodId)
						// 加载成团确认时间
						const selectedPeriod = this.availablePeriods.find(p => p.id === periodItem.periodId)
						if (selectedPeriod) {
							if (selectedPeriod.confirmationTime !== undefined) {
								this.confirmationTime = selectedPeriod.confirmationTime
								console.log(' 已加载成团确认时间:', this.confirmationTime)
							}
							// 保存初始每期服务承载最大团数（只在第一次选择时保存）
							if (this.initialGroupCount === null && selectedPeriod.maxGroupsPerService) {
								this.initialGroupCount = selectedPeriod.maxGroupsPerService
								this.maxGroupsPerService = selectedPeriod.maxGroupsPerService
								console.log('✅ 三类商家申请调用 - 保存初始每期服务承载最大团数:', this.initialGroupCount)
							}
							// 保存初始渠道申请截止天数（只在第一次选择时保存）
							if (this.initialApplicationDeadline === null && selectedPeriod.applicationDeadline) {
								this.initialApplicationDeadline = selectedPeriod.applicationDeadline
								this.applicationDeadline = selectedPeriod.applicationDeadline
								console.log('✅ 三类商家申请调用 - 保存初始渠道申请截止天数:', this.initialApplicationDeadline)
							}
						}
					}
				} else {
					const idIndex = this.selectedPeriodIds.indexOf(periodItem.periodId)
					if (idIndex !== -1) {
						this.selectedPeriodIds.splice(idIndex, 1)
					}
				}

				// 强制触发视图更新
				this.$forceUpdate()
			}
		},

		// 加载选中班期的源商家联系人（三类商家申请调用时使用）
		loadSourceContactFromPeriod(periodId) {
			// 从 availablePeriods 中查找对应的班期
			const selectedPeriod = this.availablePeriods.find(p => p.id === periodId)
			if (selectedPeriod && selectedPeriod.contact && Array.isArray(selectedPeriod.contact)) {
				// 提取联系人信息并保存到 sourceContactList
				this.sourceContactList = selectedPeriod.contact.map(c => ({
					category: c.category || '',
					name: c.name || '',
					phone: c.phone || '',
					businessType: c.businessType || this.sourceMerchantType,
					productType: c.productType !== undefined && c.productType !== null
						? Number(c.productType)
						: (Number(this.productType) || undefined)
				}))
				console.log('✅ 已加载源商家联系人信息:', this.sourceContactList)
			} else {
				console.warn('⚠️ 未找到源商家联系人信息，periodId:', periodId)
				this.sourceContactList = []
			}
		},

		// 格式化月日显示
		formatMonthDay(dateString) {
			const parts = dateString.split('-')
			if (parts.length >= 3) {
				return `${parts[1]}/${parts[2]}`
			}
			return dateString
		},

		// 格式化年份显示
		formatYear(dateString) {
			const parts = dateString.split('-')
			if (parts.length >= 1) {
				return `${parts[0]}年`
			}
			return dateString
		},

		// 获取选中班期的价格（取第一个选中的班期价格）
		getSelectedPeriodPrice() {
			const selectedPeriod = this.selectedDates && this.selectedDates.find(item => item.isSelected)
			return selectedPeriod ? selectedPeriod.periodData.price : 0
		}
	}
}
</script>

<style lang="scss" scoped>
.page-top-bg {
	position: fixed;
	top: 0;
	left: 0;
	width: 750rpx;
	height: 280rpx;
	background: #FC642F;
	box-shadow: 0rpx 4rpx 24rpx 0rpx rgba(216, 216, 216, 0.72);
	backdrop-filter: blur(0px);
	// z-index: 1; // 在内容与导航栏之下/之上按需调节；透明导航栏z-index更高
	pointer-events: none; // 不拦截点击
}

.content-area {
	background: #eeeeee;
}

// 全局变量定义
$primary-color: #3FBDA3; // 主题绿，贴近设计稿
$secondary-color: #82A0F7;
$danger-color: #FF3B30;
$warning-color: #FC642F;
$success-color: #4CAF50;
$gray-color: #8E8E93;
$light-gray: #F1F1F1;
$border-color: #EEEEEE;
$text-primary: #333333;
$text-secondary: #999999;
$text-light: #FFFFFF;
$radius-base: 12rpx;
$radius-large: 20rpx;
$shadow-sm: 0 2rpx 10rpx rgba(0, 0, 0, 0.08);
$shadow-md: 0rpx -4rpx 14rpx 0rpx rgba(241, 241, 241, 0.5);
$transition-base: all 0.3s ease;

// 主容器样式
.period-create-container {
	// height: 100vh;
	// background-color: $light-gray;
	position: relative;
}

// 加载状态
.loading-container {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(255, 255, 255, 0.9);
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	z-index: 1000;

	.loading-text {
		margin-top: 20rpx;
		font-size: 28rpx;
		color: $text-secondary;
	}
}

// 主要内容区域
.main-content {
	// padding-top: 20rpx;
	padding-bottom: 180rpx;
	// padding-left: 20rpx;
	// padding-right: 20rpx;
	// min-height: calc(100vh - 200rpx);
	// z-index: 2;
}

.main-top-period {
	margin: 24rpx;
	padding: 28rpx;
	background: #FFFFFF;
	border-radius: 20rpx;
}

// 产品信息卡片包装器
.product-card-wrapper {
	padding: 5rpx;
}

// 通用区块样式
.section {
	// background-color: $text-light;
	// border-radius: $radius-large;
	// margin-bottom: 20rpx;
	// overflow: hidden;
	// border: 1rpx solid #f1f1f1;
	// box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
	// transition: $transition-base;
	background: #ffffff;
	margin: 24rpx;
	border-radius: 20rpx;

	&-header {
		display: flex;
		// justify-content: space-between;
		align-items: center;
		padding: 28rpx;
		// border-bottom: 1rpx solid #f5f5f5;

		&__left {
			display: flex;
			align-items: center;
		}

		&__icon {
			width: 30rpx;
			height: 30rpx;
			margin-right: 20rpx;
			font-size: 28rpx;
			color: $primary-color;
			display: flex;
			align-items: center;
			justify-content: center;
			background: #eeeeee;
		}

		&__title {
			font-size: 28rpx;
			font-weight: 600;
			color: $text-primary;
		}

		&__add-btn {
			padding: 8rpx 20rpx;
			background: rgba(255, 255, 255, 0.1);
			border-radius: 8rpx;
			color: #FC642F;
			font-size: 24rpx;
			border: 1rpx solid #FC642F;

			&:active {
				transform: scale(0.95);
				background-color: rgba($primary-color, 0.15);
			}
		}

		&__buttons {
			display: flex;
			gap: 15rpx;
		}

		&__btn {
			border: none;
			border-radius: 38rpx;
			padding: 0 20rpx;
			height: 70rpx;
			line-height: 70rpx;
			font-size: 26rpx;
			display: inline-flex;
			align-items: center;
			justify-content: center;
			border: 1rpx solid rgba($primary-color, 0.35);
			color: $primary-color;
			background-color: rgba($primary-color, 0.06);
			box-shadow: 0 2rpx 8rpx rgba($primary-color, 0.15);
			transition: $transition-base;

			&:active {
				transform: scale(0.95);
				background-color: rgba($primary-color, 0.15);
			}
		}
	}

	&-description {
		font-size: 24rpx;
		color: $text-secondary;
		padding: 0rpx 30rpx 20rpx;
		line-height: 1.5;
	}
}

// 班期卡片容器
.period-cards-container {
	padding: 20rpx 30rpx 20rpx 0rpx;
	display: flex;
	flex-wrap: nowrap; // 默认单行
	gap: 15rpx;
	overflow-x: auto;
	-webkit-overflow-scrolling: touch;
	white-space: nowrap;
	scrollbar-width: none;

	&::-webkit-scrollbar {
		display: none;
		height: 0;
		width: 0;
	}

	&.expanded {
		flex-wrap: wrap; // 展开后多行显示
		overflow-x: visible;
		white-space: normal;
	}
}

// 班期卡片样式
.period-card {
	position: relative;
	flex: 0 0 104rpx; // 固定卡片宽度
	width: 104rpx;
	min-width: 104rpx;
	background-color: #f8f8f8;
	border: 1rpx solid #e0e0e0;
	border-radius: 8rpx;
	// padding: 16rpx 6rpx;
	transition: all 0.3s ease;
	box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.05);
	// 禁用点击，只能通过"全部班期"按钮进入日历修改
	pointer-events: none;
	cursor: default;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 120rpx;
	min-height: 120rpx;

	&:active {
		transform: scale(0.95);
	}

	&.selected {
		border: none !important;
		background-color: #f8f8f8 !important;
		color: #FF6B35 !important;
		box-shadow: none !important;
	}

	// A类日期选择：选中状态不显示橙色边框
	// 注意：需要同时有 selected 和 a-class-selected 类时，a-class-selected 的样式优先级更高
	&.selected.a-class-selected {
		border-color: #e0e0e0 !important;
		background-color: #f8f8f8 !important;
		color: #333333 !important;
		box-shadow: none !important;
	}

	&.disabled {
		opacity: 0.5;
		background-color: #f0f0f0 !important;
		border-color: #d0d0d0 !important;
		// 允许点击，但保持禁用样式
		// pointer-events: none;
		cursor: not-allowed;

		.period-card__month-day {
			color: #999999 !important;
		}

		.period-card__week {
			color: #999999 !important;
		}
	}

	&__date {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 8rpx;
	}

	&__month-day {
		font-size: 24rpx;
		font-weight: 400;
		color: #FF6B35;
		line-height: 1.2;
		text-align: center;
	}

	&__week {
		text-align: center;
		font-size: 24rpx;
		color: #FF6B35;
		margin-bottom: 8rpx;
		font-weight: 400;
	}

	&__selected-icon {
		position: absolute;
		bottom: 0;
		right: 0;
		width: 0;
		height: 0;
		border-left: 20rpx solid transparent;
		border-bottom: 20rpx solid #FF6B35;
		display: flex;
		align-items: center;
		justify-content: center;

		&::after {
			content: '✓';
			position: absolute;
			bottom: 2rpx;
			right: 2rpx;
			color: #ffffff;
			font-size: 12rpx;
			font-weight: bold;
		}
	}
}

// 日期角标（数量）
.period-badge {
	position: absolute;
	top: -8rpx;
	right: -8rpx;
	min-width: 28rpx;
	height: 28rpx;
	// padding: 0 6rpx;
	background-color: #FF6B35;
	color: #ffffff;
	border-radius: 20rpx;
	font-size: 18rpx;
	line-height: 28rpx;
	text-align: center;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 2rpx 8rpx rgba(255, 107, 53, 0.35);
	z-index: 2;
}

// 班期管理按钮样式
.period-management-btn {
	flex: 0 0 104rpx;
	width: 104rpx;
	min-width: 104rpx;
	background-color: #FF6B35;
	border: none;
	border-radius: 8rpx;
	// padding: 16rpx 6rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	min-height: 110rpx;
	transition: all 0.3s ease;
	box-shadow: 0 2rpx 8rpx rgba(255, 107, 53, 0.3);
	margin-left: auto; // 固定在最右边

	&:active {
		transform: scale(0.95);
		background-color: #e55a2b;
	}

	text {
		color: #ffffff;
		font-size: 24rpx;
		font-weight: 400;
		text-align: center;
	}
}

// 全部班期（始终最右侧，点击展开）
.all-periods-button {
	// flex: 0 0 104rpx;
	// padding: 16rpx 6rpx;
	padding: 8rpx;
	bottom: 20rpx;
	width: 90rpx;
	height: 112rpx;
	background-color: #ffffff;
	// border: 1rpx solid #FF6B35;
	border-radius: 8rpx;
	display: inline-flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	color: #FF6B35;
	font-size: 26rpx;
	position: absolute;
	right: 0;
	z-index: 2;
	background-clip: padding-box;
	order: 9999; // 始终在最右侧
	box-shadow: -8rpx 0rpx 8rpx 0rpx rgba(0, 0, 0, 0.1);

	text {
		line-height: 1.2;
	}
}

// 占位标签（防止被全部班期按钮遮挡）
.all-periods-button-spacer {
	flex: 0 0 70rpx;
	width: 70rpx;
	height: 112rpx;
}

// 渠道价格信息样式
.channel-price-info {
	padding: 20rpx 30rpx;
	background-color: rgba($primary-color, 0.05);
	border-top: 1rpx solid rgba($primary-color, 0.1);
	display: flex;
	align-items: center;
	justify-content: flex-start;

	.channel-price-label {
		font-size: 26rpx;
		color: $text-secondary;
		margin-right: 10rpx;
	}

	.channel-price-value {
		display: inline-flex;
		align-items: baseline;
		color: $primary-color;

		.currency {
			font-size: 28rpx;
			font-weight: 600;
			margin-right: 2rpx;
		}

		.price-int {
			font-size: 32rpx; // 比右边大4rpx
			font-weight: 700; // 左边加粗
			line-height: 1;
		}

		.price-dec {
			font-size: 28rpx;
			font-weight: 600;
			line-height: 1;
		}

		.per {
			font-size: 26rpx;
			font-weight: 500;
			margin-left: 4rpx;
			color: $text-secondary;
		}
	}
}

// 空状态样式
.empty-dates {
	padding: 40rpx 30rpx;
	text-align: center;

	.empty-text {
		font-size: 28rpx;
		color: $text-secondary;
	}
}

// 表单组样式
.form-group {
	padding: 20rpx 30rpx;

	&__label {
		font-size: 28rpx;
		color: #333333;
		// margin-bottom: 10rpx;
	}

	&__picker {
		color: #999999;
		// border-bottom: 1rpx solid #f0f0f0;
		transition: $transition-base;
		font-size: 28rpx;
		display: flex;
		align-items: center;

		&:active {
			background-color: #f8f8f8;
		}
	}

	&__input-wrapper {
		margin-top: 10rpx;
	}

	&__input {
		width: 100%;
		padding: 15rpx 20rpx;
		border: 1rpx solid #e0e0e0;
		border-radius: 8rpx;
		font-size: 28rpx;
		color: $text-primary;
		background-color: #f8f9fa;
		transition: $transition-base;

		&:focus {
			border-color: $primary-color;
			background-color: $text-light;
			outline: none;
		}

		&::placeholder {
			color: #999;
			font-size: 26rpx;
		}
	}
}

// 数字输入组样式
.number-input-group {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 30rpx;
	border-top: 1rpx dashed #eee;
	transition: $transition-base;

	&__label {
		font-size: 28rpx;
		color: $text-primary;
		flex: 1;
		font-weight: 500;
	}

	&__control {
		display: flex;
		align-items: center;
	}

	&__buttons {
		display: flex;
		align-items: center;
		// background: #fafafa;
		// border: 1rpx solid #eee;
		border-radius: 40rpx;
		padding: 0 10rpx;
		transition: $transition-base;

		&:hover {
			border-color: $primary-color;
		}
	}

	&__input {
		width: 80rpx;
		text-align: center;
		// margin: 0 10rpx;
		font-size: 28rpx;
		color: $text-primary;
		border-bottom: 0;
		font-weight: 600;
	}

	&__unit {
		font-size: 30rpx;
		color: $text-primary;
		// margin-left: 20rpx;
		font-weight: 500;
	}

	&__display {
		display: flex;
		align-items: center;
		padding: 10rpx 20rpx;
		background: #f5f5f5;
		border-radius: 8rpx;
	}

	&__value {
		font-size: 32rpx;
		color: $text-primary;
		font-weight: 600;
		margin-right: 8rpx;
	}
}

.margin-top-large {
	margin-top: 0rpx;
}

// 数字输入按钮样式
.number-input-decrement {
	width: 40rpx;
	height: 40rpx;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	color: #ffffff;
	transition: all 0.3s;
	background-color: #FC642F; // 橙色

	&.disabled {
		background-color: #999999;
	}
}

.number-input-increment {
	width: 40rpx;
	height: 40rpx;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	color: #ffffff;
	transition: all 0.3s;
	background-color: #FC642F; // 橙色

	&.disabled {
		background-color: #999999;
	}
}

// 调整输入框样式
.number-input-value,
.number-input-group__input {
	width: 50rpx;
	text-align: center;
	font-size: 28rpx;
	color: #666666;
	border: none;
	background: transparent;
	font-weight: 400;
}

// 工作人员相关样式
.staff-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 30rpx;
	border-bottom: 1rpx dashed #eee;
	transition: $transition-base;

	&:hover {
		background-color: #f8f8f8;
	}

	&__info {
		display: flex;
		flex-direction: column;
		flex: 1;
	}

	&__name {
		font-size: 28rpx;
		color: $text-primary;
		font-weight: 500;
		margin-bottom: 5rpx;
	}

	&__tel {
		font-size: 26rpx;
		color: $text-secondary;
	}

	&__delete {
		color: $danger-color;
		font-size: 26rpx;
		padding: 8rpx 16rpx;
		border-radius: 16rpx;
		background-color: rgba($danger-color, 0.1);
		transition: $transition-base;

		&:active {
			background-color: rgba($danger-color, 0.2);
			transform: scale(0.95);
		}
	}
}

// 添加联系人表单样式
.staff-add-form {
	padding: 20rpx 30rpx;
	background-color: #f8f9fa;
	border-top: 1rpx solid #eee;

	&__title {
		font-size: 28rpx;
		font-weight: 600;
		color: $text-primary;
		margin-bottom: 20rpx;
	}

	&__fields {
		margin-bottom: 20rpx;
	}

	&__field {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
	}

	&__label {
		width: 120rpx;
		font-size: 26rpx;
		color: #000000;
		font-weight: 700;
	}

	&__input {
		flex: 1;
		height: 60rpx;
		width:220rpx;
		padding: 0 20rpx;
		border: 1rpx solid #ddd;
		border-radius: 8rpx;
		font-size: 26rpx;
		color: $text-primary;
		background-color: $text-light;
		line-height: 60rpx;

		&:focus {
			border-color: $primary-color;
			outline: none;
		}
	}

	&__actions {
		display: flex;
		justify-content: flex-end;
		gap: 20rpx;
	}

	&__cancel {
		padding: 10rpx 30rpx;
		border: 1rpx solid $border-color;
		border-radius: 20rpx;
		background-color: $text-light;
		color: $text-secondary;
		font-size: 26rpx;
		transition: $transition-base;
		flex:1;
		&:active {
			background-color: #f5f5f5;
		}
	}

	&__confirm {
		padding: 10rpx 30rpx;
		border: none;
		border-radius: 20rpx;
		background-color: $primary-color;
		color: $text-light;
		font-size: 26rpx;
		transition: $transition-base;
		flex:1;
		&:active {
			background-color: darken($primary-color, 10%);
			transform: scale(0.98);
		}
	}
}

.staff-add-section__button {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 15rpx 0;
	margin: 20rpx 30rpx;
	border: 2rpx dashed $primary-color;
	border-radius: 12rpx;
	background-color: rgba($primary-color, 0.05);
	transition: $transition-base;

	&:active {
		background-color: rgba($primary-color, 0.1);
	}

	&-icon {
		font-size: 32rpx;
		color: $primary-color;
		margin-right: 10rpx;
	}

	&-text {
		font-size: 28rpx;
		color: $primary-color;
	}
}

// 价格输入组样式
.price-input-group {
	padding: 20rpx 30rpx;

	&__row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	&__label {
		min-width: 260rpx;
		font-size: 28rpx;
		color: #000000;
		// font-weight: 700;
		display: flex;
		align-items: center;
		margin-top: 10rpx;
	}

	&__input-wrapper {
		display: flex;
		align-items: center;
		border: 1rpx solid #f0f0f0;
		padding: 0rpx 20rpx;
	}

	&__divider {
		height: 1rpx;
		background-color: #f0f0f0;
		margin: 20rpx 0;
	}

	&__input {
		// width: 200rpx;
		text-align: right;
		font-weight: 400;
		font-size: 28rpx;
		color: #999999;
		// border: 1rpx solid #f0f0f0;
		padding: 10rpx;
		transition: $transition-base;

		&.has-value,
		&:focus {
			// border-bottom-color: $primary-color;
			color: #000000;
			font-weight: 600;
		}
	}

	&__currency {
		// font-weight: 600;
		margin-left: 10rpx;
		font-size: 28rpx;
		color: #000000;
		flex-shrink: 0;
	}

	&__estimate {
		// font-weight: 600;
		font-size: 28rpx;
		color: #000000;
		min-width: 200rpx;
		text-align: right;

		&.text-orange {
			color: #FF6B35;
		}

		&.text-red {
			color: $danger-color;
		}
	}

	&__description {
		font-size: 24rpx;
		color: $text-secondary;
		// position: relative;
		// top: -10rpx;
		// line-height: 1.4;
	}

	&__question {
		font-size: 36rpx;
		margin-left: 10rpx;
		color: $warning-color;
		cursor: pointer;
		transition: $transition-base;

		&:active {
			transform: scale(1.1);
		}
	}
}

// 协议确认样式
.agreement-section {
	display: flex;
	align-items: flex-start;
	padding: 0rpx 30rpx 0rpx 20rpx;
	margin: 20rpx 0;

	checkbox {
		width: 40rpx;
		height: 40rpx;
		margin-right: 20rpx;
	}

	&__text {
		color: $gray-color;
		font-size: 28rpx;
	}

	&__link {
		color: #0081ff;
		font-size: 28rpx;
		// text-decoration: underline;
		cursor: pointer;
		transition: $transition-base;

		&:active {
			color: darken($primary-color, 10%);
		}
	}
}

// 接送区域选择样式
.gather-area-select {
	display: flex;
	gap: 20rpx;
	padding: 20rpx 30rpx;
}

.gather-area-picker-wrapper {
	flex: 1;
	min-width: 0;
	/* 防止flex子项溢出 */
}

.gather-area-picker {
	padding: 15rpx 20rpx;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-size: 26rpx;
	color: $text-primary;
	width: 160rpx;
	text-align: center;

	.picker-value {
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		min-width: 0;
		/* 防止flex子项溢出 */
	}

	.picker-arrow {
		font-size: 20rpx;
		color: #999;
		margin-left: 10rpx;
		flex-shrink: 0;
		/* 防止箭头被压缩 */
	}
}

// 集散地址地图选择样式
.gather-address-select {
	display: flex;
	align-items: center;
	padding: 0rpx 20rpx 20rpx 20rpx;
	gap: 10rpx;
}

.gather-address-content {
	flex: 1;
	min-height: 80rpx;
	border-radius: 4rpx;
	padding: 0rpx 20rpx;
	display: flex;
	align-items: center;
	justify-content: flex-start;
	cursor: pointer;
}

.gather-address-display {
	display: flex;
	flex-direction: column;
	gap: 4rpx;
	width: 100%;
}

.gather-address-name {
	font-size: 26rpx;
	color: #333;
	font-weight: 700;
	line-height: 1.4;
}

.gather-address-location {
	font-size: 24rpx;
	color: #666;
	line-height: 1.4;
	font-weight: 700;
	margin-left: 0;
}

.gather-address-placeholder {
	font-size: 26rpx;
	color: #999;
	line-height: 1.4;
}

.gather-location-icon {
	background: #3FBDA3;
	display: flex;
	justify-content: center;
	align-items: center;
	height: 60rpx;
	width: 40rpx;
	color: white;
	padding: 0rpx 8rpx;
	border-radius: 8rpx;
}

// 小组名额设置通知样式
.group-quota-notice {
	padding: 20rpx 30rpx;
	background-color: rgba(#FFE5D9, 0.3);
	border-left: 4rpx solid #FF6B35;
	margin: 20rpx 30rpx;
	border-radius: 8rpx;

	.notice-text {
		font-size: 24rpx;
		color: #666;
		line-height: 1.6;
	}
}

// 小组名额摘要样式（三类商家）
.group-quota-summary {
	padding: 20rpx 30rpx;
	// background-color: rgba($primary-color, 0.05);
	// border-left: 4rpx solid $primary-color;
	margin: 20rpx 0rpx;
	border-radius: 8rpx;

	.summary-text {
		font-size: 26rpx;
		color: $text-primary;
		font-weight: 600;
		display: block;
		margin-bottom: 10rpx;
	}

	.summary-hint {
		font-size: 22rpx;
		color: #999;
		line-height: 1.5;
		display: block;
	}
}

// 地图选择区域样式
.map-select-area {
	padding: 20rpx 30rpx;
	min-height: 200rpx;
}

.map-placeholder {
	height: 200rpx;
	background-color: #f5f5f5;
	border: 2rpx dashed #ccc;
	border-radius: 12rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	gap: 15rpx;
	cursor: pointer;
	transition: all 0.3s ease;

	&:active {
		background-color: #eee;
	}

	.map-placeholder-text {
		font-size: 28rpx;
		color: #999;
	}

	.map-icon {
		font-size: 48rpx;
		color: $primary-color;
	}
}

// 底部按钮样式
.bottom-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	padding: 30rpx;
	padding-bottom: 60rpx;
	background-color: $text-light;
	box-shadow: $shadow-md;
	display: flex;
	justify-content: space-between;
	align-items: center;
	z-index: 100;

	&__back {
		width: 25%;
		height: 76rpx;
		line-height: 76rpx;
		text-align: center;
		color: $text-secondary;
		font-size: 28rpx;
		border: 1rpx solid $border-color;
		border-radius: 38rpx;
		background-color: $text-light;
		transition: $transition-base;

		&:active {
			background-color: #3FBDA3;
			transform: scale(0.98);
		}
	}

	&__middle {
		width: 30%;
		height: 76rpx;
		line-height: 76rpx;
		background-color: #FC642F;
		color: $text-light;
		text-align: center;
		border-radius: 38rpx;
		font-size: 28rpx;
		box-shadow: 0 4rpx 12rpx rgba($primary-color, 0.3);
		transition: $transition-base;

		&:active {
			transform: scale(0.98);
			box-shadow: 0 2rpx 8rpx rgba($primary-color, 0.3);
		}

		&.disabled {
			background-color: $gray-color;
			box-shadow: none;
			opacity: 0.6;

			&:active {
				transform: none;
			}
		}
	}

	&__submit {
		width: 30%;
		height: 76rpx;
		line-height: 76rpx;
		background-color: $primary-color;
		color: $text-light;
		text-align: center;
		border-radius: 38rpx;
		font-size: 28rpx;
		box-shadow: 0 4rpx 12rpx rgba($primary-color, 0.3);
		transition: $transition-base;

		&:active {
			transform: scale(0.98);
			box-shadow: 0 2rpx 8rpx rgba($primary-color, 0.3);
		}

		&.disabled {
			background-color: $gray-color;
			box-shadow: none;
			opacity: 0.6;

			&:active {
				transform: none;
			}
		}
	}
}

.section-header__title {
	font-size: 28rpx;
	font-weight: 700;
	color: #333333;
}

.section-item {
	padding: 0rpx 28rpx;

	.section-item-top {
		display: flex;
		align-items: center;
		padding: 24rpx 0rpx;
	}

	.section-item-bottom {
		display: flex;
		font-size: 28rpx;
		padding: 0rpx 0rpx 28rpx 0rpx;

		.section-item-left {
			color: #FC642F;
			display: flex;
			flex: 1
		}

		.section-item-right {
			color: #666666;
		}
	}
}

.working-box {
	padding: 0rpx 28rpx 20rpx 28rpx;

	.working-item {
		display: flex;
		align-items: center;
		padding: 24rpx 28rpx;
		height: 88rpx;
		background: #F4F4F4;
		margin-bottom: 20rpx;
		border-radius: 12rpx;
		font-size: 28rpx;

		.working-info {
			height: 88rpx;
			display: flex;
			align-items: flex-start;
			justify-content: space-around;
			flex-direction: column;
			margin-left: 20rpx;
			flex: 1;

			.woking-info-top {
				font-size: 28rpx;
				font-weight: 600;
				display: flex;
				align-items: center;

				text {
					margin-left: 16rpx;
					font-size: 20rpx;
					color: #FC642F;
					padding: 4rpx 12rpx;
					background: rgba(252, 100, 47, 0.1);
					border-radius: 4rpx;

				}
			}

			.woking-info-bottom {
				color: #999999;
				font-size: 24rpx;
			}

		}

		.working-btn {

			// margin-right:28rpx;
			.working-delete {
				width: 104rpx;
				height: 48rpx;
				background: rgba(255, 255, 255, 0.1);
				border-radius: 4rpx;
				border: 1rpx solid #FC642F;
				text-align: center;
				line-height: 48rpx;
				color: #FC642F;
				font-size: 22rpx;
				border-radius: 8rpx;
			}
		}

	}

	.working-none {
		padding: 40rpx 0;
		text-align: center;
		font-size: 26rpx;
		color: #999999;
	}
}

.home-icon {
	width: 28rpx;
	height: 28rpx;

}

.working-bottom {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0rpx 28rpx 36rpx 30rpx;

	.working-bottom-top {
		font-size: 24rpx;
		color: #999999;
	}

	.working-bottom-bottom {
		width: 104rpx;
		height: 48rpx;
		background: rgba(255, 255, 255, 0.1);
		border-radius: 4rpx;
		border: 1rpx solid #FC642F;
		text-align: center;
		line-height: 48rpx;
		border-radius: 8rpx;
		color: #FC642F;
	}
}

.section-header__font_icon {
	color: #000000
}

// 工作人员配置弹窗样式
.staff-popup-container {
	background-color: #ffffff;
	border-radius: 20rpx 20rpx 0 0;
	min-height: 500rpx;
	max-height: 80vh;
	display: flex;
	flex-direction: column;
}

.staff-popup-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 30rpx 40rpx;
	border-bottom: 1rpx solid #eee;
}

.staff-popup-title {
	font-size: 32rpx;
	font-weight: 700;
	color: #333333;
}

.staff-popup-content {
	flex: 1;
	padding: 30rpx 40rpx;
	max-height: 60vh;
}
</style>
